文章目录
题目

方法一:常规做法:
java
class Solution {
public String replaceSpace(String s) {
int len = s.length() ;
StringBuffer str = new StringBuffer();
for(int i = 0 ; i < len ; i++){
if(s.charAt(i) == ' ') str.append("%20");//遇到空格就在尾部拼接%20
else str.append(s.charAt(i));//遇到字符就在尾部正常拼接字符
}
return str.toString();
}
}
方法二:双指针做法

java
class Solution {
public String replaceSpace(String s) {
int len = s.length() ;
StringBuffer str = new StringBuffer(s);
if( len == 0 ) return "";
for(int i = 0 ; i< len ; i++)
if(s.charAt(i)==' ') str.append(" ");//扩充空间,空格数量2倍
String string = str.toString();
char[] strs = string.toCharArray();
int left = s.length()-1;
int right = str.length()-1;
while(left >= 0 ){
if(str.charAt(left) == ' '){
strs[right--] = '0';
strs[right--] = '2';
strs[right] = '%';
}else strs[right] = strs[left];
right--;
left--;
}
return new String(strs);
}
}