**题目:**URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。)
示例:
提示:
- 字符串长度在[0, 500000]范围内。
方法一:直接用String的API
效率太差,而且要求也不是用这种方法,不过第一反应就是用这种方法做的。
class Solution {
public String replaceSpaces(String S, int length) {
return S.substring(0, length).replaceAll(" ", "%20");
}
}
方法二:字符数组
class Solution {
public String replaceSpaces(String S, int length) {
char[] ch = new char[length * 3];
int index = 0;
for (int i = 0; i < length; i++) {
char c = S.charAt(i);
if (c == ' ') {
ch[index++] = '%';
ch[index++] = '2';
ch[index++] = '0';
} else {
ch[index] = c;
index++;
}
}
return new String(ch, 0, index);
}
}
方法三:使用StringBuilder
class Solution {
public String replaceSpaces(String S, int length) {
//
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
char ch = S.charAt(i);
if (ch == ' ') {
sb.append("%20");
continue;
}
sb.append(ch);
}
return sb.toString();
}
}