剑指 Offer 05. 替换空格
class Solution {
public String replaceSpace(String s) {
StringBuilder str = new StringBuilder(s);
int p1 = str.length() - 1;
for(int i = 0; i <= p1; i++){
if(str.charAt(i) == ' ')
str.append(" ");
}
int p2 = str.length() - 1;
while(p1 <= p2 && p1 >= 0){
char c = str.charAt(p1--);
if(c == ' '){
str.setCharAt(p2--, '0');
str.setCharAt(p2--, '2');
str.setCharAt(p2--, '%');
}else{
str.setCharAt(p2--, c);
}
}
return str.toString();
}
}
思路:
- 指针p1指向原字符串的末位
- 遍历数组,每有一个空格,就在字符串末尾添加两个空格
- 指针p2指向新字符串的末位
- p1前向遍历
- 遇到非空格字符就添加到p2处,p2--;
- 遇到空格,p2边向前移动,边依次添加字符0,2,%;
- 当p1和p2相遇或p1走完数组时结束