替换空格
题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
注意输入类型,输入的str为StringBuffer,相关操作有设置长度,setCharAt()等,随后需要调用toString()返回。
方法一
直接在原数组上替换 :
时间O(N)
空间O(1)
public class Solution{
public String replaceSpace(StringBuffer str){
int count = 0;
int len = str.length();
for(int i = 0; i < len; i++){
if(str.charAt(i) == ' '){
count++;
}
}
int newindex = len + count * 2 - 1;
str.setLength(newindex +1); // 一定要重新设置长度!
int oldindex = len - 1;
while(newindex >= 0 && oldindex >=0 && newindex >oldindex) {
if(str.charAt(oldindex) == ' '){
str.setCharAt(newindex--, '0');
str.setCharAt(newindex--, '2');
str.setCharAt(newindex--, '%');
}else{
str.setCharAt(newindex--, str.charAt(oldindex));
}
oldindex--;
}
return str.toString();
}
}