随笔- 509  文章- 0  评论- 151  阅读- 22万 

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 }
复制代码

 

 posted on   zhuli19901106  阅读(425)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示