首页 > 其他 > 详细

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

时间:2014-03-18 11:55:35      阅读:255      评论:0      收藏:0      [点我收藏+]

2014-03-18 01:36

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

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

代码:

bubuko.com,布布扣
 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 }
bubuko.com,布布扣

《Cracking the Coding Inteview》——第1章:数组和字符串——题目4,布布扣,bubuko.com

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

原文:http://www.cnblogs.com/zhuli19901106/p/3606672.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!