经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C++ » 查看文章
C++实现LeetCode(186.翻转字符串中的单词之二)
来源:jb51  时间:2021/8/4 17:55:50  对本文有异议

[LeetCode] 186. Reverse Words in a String II 翻转字符串中的单词之二

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

Example:

Input:  ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]

Note: 

  • A word is defined as a sequence of non-space characters.
  • The input string does not contain leading or trailing spaces.
  • The words are always separated by a single space.

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

这道题让我们翻转一个字符串中的单词,跟之前那题 Reverse Words in a String 没有区别,由于之前那道题就是用 in-place 的方法做的,而这道题反而更简化了题目,因为不考虑首尾空格了和单词之间的多空格了,方法还是很简单,先把每个单词翻转一遍,再把整个字符串翻转一遍,或者也可以调换个顺序,先翻转整个字符串,再翻转每个单词,参见代码如下:

解法一:

  1. class Solution {
  2. public:
  3. void reverseWords(vector<char>& str) {
  4. int left = 0, n = str.size();
  5. for (int i = 0; i <= n; ++i) {
  6. if (i == n || str[i] == ' ') {
  7. reverse(str, left, i - 1);
  8. left = i + 1;
  9. }
  10. }
  11. reverse(str, 0, n - 1);
  12. }
  13. void reverse(vector<char>& str, int left, int right) {
  14. while (left < right) {
  15. char t = str[left];
  16. str[left] = str[right];
  17. str[right] = t;
  18. ++left; --right;
  19. }
  20. }
  21. };

我们也可以使用 C++ STL 中自带的 reverse 函数来做,先把整个字符串翻转一下,然后再来扫描每个字符,用两个指针,一个指向开头,另一个开始遍历,遇到空格停止,这样两个指针之间就确定了一个单词的范围,直接调用 reverse 函数翻转,然后移动头指针到下一个位置,在用另一个指针继续扫描,重复上述步骤即可,参见代码如下:

解法二:

  1. class Solution {
  2. public:
  3. void reverseWords(vector<char>& str) {
  4. reverse(str.begin(), str.end());
  5. for (int i = 0, j = 0; i < str.size(); i = j + 1) {
  6. for (j = i; j < str.size(); ++j) {
  7. if (str[j] == ' ') break;
  8. }
  9. reverse(str.begin() + i, str.begin() + j);
  10. }
  11. }
  12. };

Github 同步地址:

https://github.com/grandyang/leetcode/issues/186

类似题目:

Reverse Words in a String III

Reverse Words in a String

Rotate Array

参考资料:

https://leetcode.com/problems/reverse-words-in-a-string-ii/

https://leetcode.com/problems/reverse-words-in-a-string-ii/discuss/53851/Six-lines-solution-in-C%2B%2B

https://leetcode.com/problems/reverse-words-in-a-string-ii/discuss/53775/My-Java-solution-with-explanation

到此这篇关于C++实现LeetCode(186.翻转字符串中的单词之二)的文章就介绍到这了,更多相关C++实现翻转字符串中的单词之二内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号