题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

*注:设给定字符串长度为n。语言:C++


解法1:正向遍历,遇到空格即进行替换,并将其后的元素相应后移。

void replaceSpace(char *str,int length) { if(length <= 0) return; char rep[] = "%20"; char *out; int cnt = 0; for(int i = 0; i < length; ++i) { if(str[i] == ' ') { for(int j = length+1; j > i; --j) str[j] = str[j-2]; length += 2; strncpy(str+i, rep, 3); } } }

时间复杂度:O(n^2),空间复杂度:O(1)


解法2:正向遍历计算空格数,再反向遍历进行空格替换。

void replaceSpace(char *str,int length) { if(length <= 0) return; int cnt = 0; for(int i = 0; i < length; ++i) { if(str[i] == ' ') cnt += 2; } for(int i = length - 1; i >= 0; --i) { if(str[i] != ' ') str[i + cnt] = str[i]; else { cnt -= 2; str[i + cnt] = '%'; str[i + cnt + 1] = '2'; str[i + cnt + 2] = '0'; } } }

时间复杂度:O(n),空间复杂度:O(1)