替换空格
题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
解法一:重新申请一个空的字符串用来存储替换后的字符串,从前往后替换,遇到空格直接替换成“%20”,其他的不变。时间复杂度O(n),空间复杂度O(n)。
class Solution {
public:
void replaceSpace(char *str,int length) {
string temp=""; //用另外一个字符串来存储
for(int i=0;i<length;i++){
if(str[i]==' ')
temp += "%20";
else
temp += str[i];
}
strcpy(str,temp.c_str());//c_str()是将c++中的字符串转为c语言字符数组
}
};
解法二:直接将源字符串进行移动,但是需要提前申请足够大的空间,计算空格的数量即可,如果从前往后移动的话,需要移动的次数明显比较多,因此考虑从后往前移动。时间复杂度O(n)。
class Solution {
public:
void replaceSpace(char *str,int length) {
int i=0,count=0,j=0;
while(str[i]!='\0'){ //统计空格数量
if(str[i]==' ')
count+=1;
i++;
}
j = i+count*2; //新字符串长度
str[j--]='\0'; //字符串末尾
i--; //i指向原字符串末尾
while(i>=0&&j>=0){ //字符串从后向前移动
if(str[i]!=' ')
str[j--]=str[i];
else{
str[j--]='0';
str[j--]='2';
str[j--]='%';
}
i--;
}
}
};

浙公网安备 33010602011771号