public class Solution {
public String replaceSpace(StringBuffer str) {
if(str.length() == 0){
return "";
}
// 不借助新的变量,后续遍历
int count = 0;
int oldLength = str.length();
for(int i = 0; i < oldLength; i ++){
if(str.charAt(i) == ' '){
count ++;
}
}
int newLength = oldLength + count * 2;
int oldIndex = oldLength - 1;
int newIndex = newLength - 1;
str.setLength(newLength);
while(oldIndex >= 0 && oldIndex < newIndex){
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();
}
}