面试题05.替换空格(简单)

请实现一个函数,把字符串 s 中的每个空格替换成”%20”。

示例 1:

输入:s = "We are happy."
输出:"We%20are%20happy."

限制:

0 <= s 的长度 <= 10000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof

思路:

  1. 直接用String内置的replaceAll即可,一句话返回
  2. 使用StringBuilder创建可变字符串
  3. 使用字符数组,每次遇到一个字符就直接放入数组,遇到空格就放%,下标++,再放2,再++,再放0即可

回看记录200604

代码1和代码3可以看看,都简单,代码3中从char数组转成string要注意,以前没转过,不太会。

代码1:

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public String replaceSpace(String s) {
StringBuilder new_str = new StringBuilder();
for(Character c:s.toCharArray()){
if(c==' ')
new_str.append("%20");
else
new_str.append(c);
}
return new_str.toString();
}
}

代码2:

1
2
3
4
5
class Solution {
public String replaceSpace(String s) {
return s.replaceAll(" ","%20");
}
}

代码2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public String replaceSpace(String s) {
int length = s.length();
char[] array = new char[length * 3];
int size = 0;
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (c == ' ') {
array[size++] = '%';
array[size++] = '2';
array[size++] = '0';
} else {
array[size++] = c;
}
}
String newStr = new String(array, 0, size);
return newStr;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/solution/mian-shi-ti-05-ti-huan-kong-ge-by-leetcode-solutio/