1.题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。
2.题目示例
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
3.思路及代码
- 思路:
- 先找出空格个数,设置新的字符串的长度
- 然后从后往前遍历进行替换即可
- 代码:
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 new_length = str.length() + 2 * count;
//新旧字符串的边界
int new_end = new_length - 1;
int old_end = str.length() - 1;
//设置新字符串的长度
str.setLength(new_length);
while(new_end >= 0 && old_end >= 0){
//进行替换
if(str.charAt(old_end) == ' '){
str.setCharAt(new_end--,'0');
str.setCharAt(new_end--,'2');
str.setCharAt(new_end--,'%');
old_end--;
}else{
//单个替换即可
str.setCharAt(new_end, str.charAt(old_end));
new_end--;
old_end--;
}
}
return str.toString();
}
}