題目描述
請實(shí)現(xiàn)一個函數(shù),將一個字符串中的空格替換成“%20”。例如油坝,當(dāng)字符串為We Are Happy.則經(jīng)過替換之后的字符串為We%20Are%20Happy
代碼實(shí)現(xiàn)
public class Solution {
public String replaceSpace(StringBuffer str) {
//先計(jì)算空格的數(shù)量
int blankNum = 0;
int len1 = str.length();
for(int i = 0;i < len1;i++){
if(str.charAt(i) == ' ')
blankNum++;
}
//擴(kuò)充str的長度
int len2 = len1 + blankNum * 2;
str.setLength(len2);
//從后往前替換
for(int i = len1-1,j = len2-1;i >= 0;i--){
if(str.charAt(i) == ' '){
str.setCharAt(j--,'0');
str.setCharAt(j--,'2');
str.setCharAt(j--,'%');
if(--blankNum == 0) break;
}else{
str.setCharAt(j--,str.charAt(i));
}
}
return str.toString();
}
}
主要思路
1职辅、從后向前移動,每個元素最多移動一次
2唬滑、主要記住幾個api:length()告唆,setLength()棺弊,charAt(i),setCharAt(i,'0')
3擒悬、代碼優(yōu)化:if(--blankNum == 0) break;