题目描述:
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
题目链接:
思路:
遍历计数空格个数,然后计算出字符串的新长度,定义n向新长度最后位置,old指向还没替换的字符串最后的位置,从后向前遍历,碰到字母就都向前走,碰到字符串old向前走,new依次插入需要替换的字符,然后向前走。
代码实现如下:
public class Solution {
public String replaceSpace(StringBuffer str) {
int count = 0;
for (int i = 0; i < str.length();i++) {
if (str.charAt(i) == ' ') {
count++;
}
}
int oldL = str.length() - 1;
int newL = str.length() + 2 * count - 1;
str.setLength(newL + 1);//设置新字符串长度
while (oldL >= 0 && newL >= 0) {
if (str.charAt(oldL) == ' ') {
str.setCharAt(newL--,'0');
str.setCharAt(newL--,'2');
str.setCharAt(newL--,'%');
oldL--;
} else {
str.setCharAt(newL--,str.charAt(oldL));
oldL--;
}
}
return str.toString();
}
}