Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

For C programmers: Try to solve it in-place in O(1) space.

Clarification:

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.
这个题如果用C++的stringstream字符串流来实现的话,会非常简单
void reverseWords(string &s) {
istringstream is(s);
string tmp;
is >> s;
while(is >> tmp) s = tmp + " " + s;
if(s[] == ' ') s = "";
}

但是,题目中对于C语言实现有更严格的要求,需要就地操作

联想到之前碰到的题目,数组旋转问题,我们是否可以用类似的思路来解决呢

对于每一个单词,都将其字母前后逆置,然后再将整个字符串逆置,这样就可以得到正确反转结果了。

但是如何处理多余的空格呢?我们可以在遍历的同时,利用快慢双指针来将空格省略掉。然后再执行逆置操作。

代码如下:

void reverseWords(string &s) {

    int i = , j = ;
int l = ;
int len = s.length();
int wordcount = ; while (true) {
while (i<len && s[i] == ' ') i++;
if (i == len) break;
if (wordcount) s[j++] = ' ';
l = j;
while (i<len && s[i] != ' ') { s[j] = s[i]; j++; i++; }
reverseword(s, l, j - );
wordcount++;
}
s.resize(j);
reverseword(s, , j - );
}

最新文章

  1. nginx启动报错:/usr/local/nginx/sbin/nginx: error while loading shared libraries: libcrypto.so.1.1: cannot open shared object file: No such file or directory
  2. WebGL入门教程(三)-webgl动画
  3. 我对Jenkins的认识
  4. XAF应用开发教程(八) 汉化与多国语言支持
  5. [转]玩转Google开源C++单元测试框架Google Test系列
  6. POJ 2265 Bee Maja (找规律)
  7. ServletContext全局变量初始化
  8. Tinkphp定时发布文章的教程
  9. μC/OS学习资料(附Ebook)
  10. Swift - 高级运算符介绍
  11. Objective-C中的面向对象编程
  12. Node.js UDP/Datagram
  13. 一起来学spring Cloud | 第一章:spring Cloud 与Spring Boot
  14. PCA,到底在做什么
  15. 【 P3952】 时间复杂度 大模拟题解
  16. DocumentBuilderFactory.newInstance() 异常解决
  17. c/c++ 智能指针 unique_ptr 使用
  18. java读取写入文件
  19. 【hdu】4521 小明序列【LIS变种】【间隔至少为d】
  20. 02.设计模式_NullObject模式

热门文章

  1. HDFS存储系统
  2. C实现类、继承、多态
  3. MyBatis 的Mapper中有小于号的处理
  4. 新版本chrome浏览器控制台怎么设置成独立的窗口
  5. python之简单主机批量管理工具
  6. Awesome Chrome 插件集锦
  7. yum安装CDH5.5 Hadoop集群
  8. 服务器部署项目出现问题:Unsupported major.minor version 52.0
  9. Openstack容器项目之Magnum
  10. Java数据类型转换浅析