题目链接
题目描述
将一个字符串中的空格替换成 “%20”。
Input:
"A B"
Output:
"A%20B"
解题思路( 考虑从右向左,遇到空格,就填充“20%“,否则将原字符移动应该呆的位置。)
① 在字符串尾部填充任意字符,使得字符串的长度等于替换之后的长度。因为一个空格要替换成三个字符(%20),所以当遍历到一个空格时,需要在尾部填充两个任意字符。
② 令 P1 指向字符串原来的末尾位置,P2 指向字符串现在的末尾位置。P1 和 P2 从后向前遍历,当 P1 遍历到一个空格时,就需要令 P2 指向的位置依次填充 02%(注意是逆序的),否则就填充上 P1 指向字符的值。从后向前遍是为了在改变 P2 所指向的内容时,不会影响到 P1 遍历原来字符串的内容。
③ 当 P2 遇到 P1 时(P2 <= P1),或者遍历结束(P1 < 0),退出。
public String replaceSpace(StringBuffer str) {
int P1 = str.length() - 1;
for (int i = 0; i <= P1; i++)
if (str.charAt(i) == ' ')
str.append(" ");
int P2 = str.length() - 1;
while (P1 >= 0 && P2 > P1) {
char c = str.charAt(P1--);
if (c == ' ') {
str.setCharAt(P2--, '0');
str.setCharAt(P2--, '2');
str.setCharAt(P2--, '%');
} else {
str.setCharAt(P2--, c);
}
}
return str.toString();
}
//我的代码
class Solution {
public:
void replaceSpace(char *str,int length) {
if(str==nullptr||length<=0)
return;
int space = 0,index;
for(int i=0;i<length;i++){
if(*(str+i)==' ')
++space;
}
index = length + 2*space;
*(str+index) = '\0';
index--;
length--;
while(length>=0){
if(*(str+length)==' '){
*(str+index) = '0';
*(str+index-1) = '2';
*(str+index-2) = '%';
index -= 2;
}else{
*(str+index) = *(str+length);
}
index--;
length--;
}
}
};
// 利用C++特性
class Solution {
public:
string replaceSpace(string s) {
int len = s.length();
if(len==0)
return s;
string res;
for(const char c:s){
if(c==' '){
res += "%20";
}else{
res += c;
}
}
return res;
}
};
- 时间复杂度:O(length) 只遍历了一遍字符串
- 空间复杂度:O(1) 没有开辟空间