LeetCode|LeetCode 每日一题 [40] 替换空格
LeetCode 替换空格 [简单]
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
来源:力扣(LeetCode)示例 1: 输入:s = "We are happy."
链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof
输出:"We%20are%20happy."
限制: 0 <= s 的长度 <= 10000
题目分析
解法1 使用Java的String的API String().replace("","");代码实现
解法2 【LeetCode|LeetCode 每日一题 [40] 替换空格】将字符串转化为字符数组,然后遍历。符合条件则直接加入即可
public class ReplaceSpace {
public static void main(String[] args) {
String s = "We are happy.";
String s2 = "We are happy.";
System.out.println(replaceSpace(s));
System.out.println(replaceSpace2(s2));
}public static String replaceSpace2(String s) {
if (s == null || s.length() == 0) {
return "";
}
int len = s.length();
char[] array = new char[len * 3];
int size = 0;
for (int i = 0;
i < len;
i++) {
char c = s.charAt(i);
if (c == ' ') {
array[size++] = '%';
array[size++] = '2';
array[size++] = '0';
} else {
array[size++] = c;
}
}
return new String(array, 0, size);
}public static String replaceSpace(String s) {
return s.replace(" ", "%20");
}
}
推荐阅读
- 每日一话(49)——一位清华教授在朋友圈给大学生的9条建议
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- leetcode|leetcode 92. 反转链表 II
- #2018.4.12#每日一问#+简宁+D03+我是怎样做读书笔记的
- 每日微习惯诞生|每日微习惯诞生 16/100
- 二叉树路径节点关键值和等于目标值(LeetCode--112&LeetCode--113)
- --木木--|--木木-- 第二课作业#翼丰会(每日一淘6+1实战裂变被动引流# 6+1模式)
- LeetCode算法题-11.|LeetCode算法题-11. 盛最多水的容器(Swift)
- 03月30日|03月30日|Day92|每日复盘
- [白雪扇贝每日一句特训班]week5复盘——相信持续的力量