面试题 01.03. URL化
URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。)
示例1:
输入:"Mr John Smith ", 13
输出:"Mr%20John%20Smith"
思路
注意:这里只说知道字符串“真实”长度,但S.length()足够存放新增字符,可能后面还有好多空格。
计算符串“真实”长度空格数,然后从后往前reset字符串,最后去除后面的空格
class Solution {
public:
string replaceSpaces(string S, int length) {
int space=0;//count the space num
for(int i=0;i<length;i++){
if(S[i]==' ') space++;
}
int j=length+2*space-1;
for(int i=length-1;i>=0;i--){
if(S[i]==' '){
S[j--] = '0';
S[j--] = '2';
S[j--] = '%';
}
else S[j--] = S[i];
}
return S.substr(0,length+2*space);//cut the string, don't let space influence the result
}
};