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

2014-03-18 01:36

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

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

代码:

 1 // 1.4 Write a method to replace all spaces in a string with '%20'.
 2 // do it in-place and backward.
 3 #include <cstdio>
 4 #include <cstring>
 5 using namespace std;
 6 
 7 class Solution {
 8 public:
 9     void replaceSpace(char *str) {
10         if (nullptr == str) {
11             return;
12         }
13 
14         int i, j;
15         int len = (int)strlen(str);
16         int cc = 0;
17         for (i = 0; i < len; ++i) {
18             if (str[i] == ' ') {
19                 ++cc;
20             }
21         }
22 
23         int tc = 0;
24         for (i = len - 1; i >= 0; --i) {
25             if (str[i] == ' ') {
26                 ++tc;
27             } else {
28                 break;
29             }
30         }
31         cc -= tc;
32 
33         j = i;
34         i = cc;
35         while (j >= 0) {
36             if (str[j] == ' ') {
37                 --cc;
38                 str[j + 2 * cc] = '%';
39                 str[j + 2 * cc + 1] = '2';
40                 str[j + 2 * cc + 2] = '0';
41             } else {
42                 str[j + 2 * cc] = str[j];
43             }
44             --j;
45         }
46         if (2 * i > tc) {
47             str[len - tc + 2 * i] = 0;
48         }
49     }
50 };
51 
52 int main()
53 {
54     char str[1000];
55     Solution sol;
56 
57     while (gets(str) != nullptr) {
58          sol.replaceSpace(str);
59         puts(str);
60     }
61 
62     return 0;
63 }

 

转载于:https://www.cnblogs.com/zhuli19901106/p/3606672.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值