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 = ;
for (i = ; i < len; ++i) {
if (str[i] == ' ') {
++cc;
}
} int tc = ;
for (i = len - ; i >= ; --i) {
if (str[i] == ' ') {
++tc;
} else {
break;
}
}
cc -= tc; j = i;
i = cc;
while (j >= ) {
if (str[j] == ' ') {
--cc;
str[j + * cc] = '%';
str[j + * cc + ] = '';
str[j + * cc + ] = '';
} else {
str[j + * cc] = str[j];
}
--j;
}
if ( * i > tc) {
str[len - tc + * i] = ;
}
}
}; int main()
{
char str[];
Solution sol; while (gets(str) != nullptr) {
sol.replaceSpace(str);
puts(str);
} return ;
}

最新文章

  1. JAVA通信系列二:mina入门总结
  2. TabControl 伸缩式菜单 仿照 uwp SplitView
  3. asp.net 字符串替换、截取和从字符串中最后某个字符 开始截取
  4. PHP规范PSR2
  5. 代理传值Delegate
  6. Oracle中用户的基本操作
  7. Linux应用程序访问字符设备驱动详细过程【转】
  8. 【HDU 5387】Clock
  9. Unable to get setting value Parameter name: profileName
  10. 结构体 row_prebuilt_t
  11. css3购物网站商品文字提示实例
  12. Oracle检查与安装操作内容
  13. Linux实战教学笔记13:定时任务补充
  14. 赵雅智_Swift(1)_swift简单介绍及类型
  15. 我和Python的Py交易》》》》》》数据类型
  16. 获取 wx.getUserInfo 接口后续将不再出现授权弹窗,请注意升级(微信小程序开发)
  17. SpringMVC+Spring+Mybatis+AngularJS 多规格保存示例代码
  18. LOJ#3023 老C的键盘
  19. 11.2-uC/OS-III添加任务到就绪队列
  20. android gradle jnilibs

热门文章

  1. VirtualBox虚拟机 host/guest 拷贝粘贴,共享剪贴板,安装guest additions
  2. java对字符串进行加密和解密(以下是来自其他博主)
  3. 软件架构中的SOA架构有哪些特点?
  4. 改Chrome的User Agent,移动版网络
  5. 使用android ndk编译x86 so在linux下使用的问题
  6. Status bar - iOS之状态栏
  7. 学习vue-cli3的项目搭建
  8. 介绍hadoop中的hadoop和hdfs命令
  9. Servlet学习笔记04——什么是重定向,servlet生命周期?
  10. python导包语句执行