您的位置:首页 > 其它

《Cracking the Coding Interview》——第1章:数组和字符串——题目4

2014-03-18 01:40 423 查看
2014-03-18 01:36

题目:给定一个字符串,将其中的空格‘ ’替换为‘%20’,你可以认为字符串尾部有足够空间来容纳新增字符。请不要额外开辟数组完成。

解法:先从前往后统计空格个数,然后从后往前填充字符,以免其他无关字符被‘%20’覆盖掉。

代码:

// 1.4 Write a method to replace all spaces in a string with '%20'.
// do it in-place and backward.
#include <cstdio>
#include <cstring>
using namespace std;

class Solution {
public:
void replaceSpace(char *str) {
if (nullptr == str) {
return;
}

int i, j;
int len = (int)strlen(str);
int cc = 0;
for (i = 0; i < len; ++i) {
if (str[i] == ' ') {
++cc;
}
}

int tc = 0;
for (i = len - 1; i >= 0; --i) {
if (str[i] == ' ') {
++tc;
} else {
break;
}
}
cc -= tc;

j = i;
i = cc;
while (j >= 0) {
if (str[j] == ' ') {
--cc;
str[j + 2 * cc] = '%';
str[j + 2 * cc + 1] = '2';
str[j + 2 * cc + 2] = '0';
} else {
str[j + 2 * cc] = str[j];
}
--j;
}
if (2 * i > tc) {
str[len - tc + 2 * i] = 0;
}
}
};

int main()
{
char str[1000];
Solution sol;

while (gets(str) != nullptr) {
sol.replaceSpace(str);
puts(str);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐