替換空格
題目描述
請實現一個函數,將一個字符串中的每個空格替換成“%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();
}
}