调用系统函数:s.replace()
创建新的字符串,遇到空格时追加"%20"
原地修改,从后往前,需要首先知道空格的个数。
/**
* 将一个字符串中的每个空格替换成“%20”
* @param str 字符串
* @return 替换后的字符串
*/
public String replaceSpace(StringBuffer str) {
int numOfSpace=0;
int originLength= str.length();
for(int i=0;i<originLength;i++){
if(str.charAt(i)==' '){
numOfSpace++;
}
}
int newLength=originLength+numOfSpace*2;
str.setLength(newLength);
for(int i=originLength-1,j=newLength-1;i>=0&&j>=i;i--){
char c=str.charAt(i);
if(c==' '){
str.setCharAt(j--,'0');
str.setCharAt(j--,'2');
str.setCharAt(j--,'%');
}else {
str.setCharAt(j--,c);
}
}
return str.toString();
}
大佬的图解,地址为:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/solution/mian-shi-ti-05-ti-huan-kong-ge-ji-jian-qing-xi-tu-/