博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Reverse Words in a String II
阅读量:4353 次
发布时间:2019-06-07

本文共 1485 字,大约阅读时间需要 4 分钟。

Problem Description:

Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.

The input string does not contain leading or trailing spaces and the words are always separated by a single space.

For example,

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

Could you do it in-place without allocating extra space?

Since this problem has guaranteed that the string does not contain all the leading and trailing spaces and all words are separated by a single space, it will be much easier to be solved in space. The idea is to reverse the whole string first. Then we visit the string from left to right, each time we meet a space, we reverse the immediate word before it.

The code is as follows.

1 class Solution { 2 public: 3     void reverseWords(string &s) { 4         reverse(s.begin(), s.end()); 5         s += ' '; 6         int i = 0, j = 0, n = s.length(); 7         while (i < n && j < n) { 8             while (j < n && s[j] != ' ') j++; 9             if (j < n) {10                 reverseBetween(s, i, j - 1);11                 i = j + 1;12                 j = i;13             }14         }15         s.resize(n - 1);16     }17 private:18     void reverseBetween(string &s, int i, int j) {19         while (i < j)20             swap(s[i++], s[j--]);21     }22 };

Note that we append a space to the reversed string to facilitate the detection of the last word.

转载于:https://www.cnblogs.com/jcliBlogger/p/4600353.html

你可能感兴趣的文章
linux使用技巧
查看>>
必背公式及常数
查看>>
利用CSS、JavaScript及Ajax实现图片预加载的三大方法
查看>>
js时间戳转时间格式
查看>>
Nginx配置文件nginx.conf中文详解(总结)
查看>>
Linux的用户态和内核态
查看>>
JavaScript原生错误及检测
查看>>
(原创) cocos2d-x 3.0+ lua 学习和工作(4) : 公共函数(3): 深度克隆clone()
查看>>
为什么写作
查看>>
整数子数组求最大和添加验证
查看>>
使用kubeadm安装Kubernetes
查看>>
Principal Component Analysis 主元分析
查看>>
JDBC原生态代码
查看>>
韩版可爱小碎花创意家居收纳挂袋
查看>>
计算机基础之硬件
查看>>
python操作mysql ------- SqlAchemy正传
查看>>
如何使用 JSP JSTL 显示/制作树(tree) 菜单
查看>>
12.5号
查看>>
lintcode-medium-Binary Tree Zigzag Level Order Traversal
查看>>
logrotate日志切割
查看>>