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?

思路:这题比另一个reverse words要简单,因为不存在多余空格的问题。

因此in-place方法很简单,先把整个字符串反转,然后依次把字符串中的每个单词再反转一次。

 1 class Solution {
 2 public:
 3     void reverseWords(string &s) {
 4         int l = 0, r = s.size() - 1;
 5         while (l < r)
 6             swap(s[l++], s[r--]);
 7         for (int i = 0, n = s.size(); i < n;)
 8         {
 9             for (r = i + 1; r < n && s[r] != ' '; r++);
10             l = i, r--;
11             i = r + 2;
12             while (l < r)
13                 swap(s[l++], s[r--]);
14         }
15     }
16 };

 

相关文章:

  • 2021-12-04
  • 2022-02-11
  • 2021-10-01
  • 2021-10-29
  • 2022-02-22
  • 2021-09-10
  • 2021-10-01
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-27
  • 2021-08-21
相关资源
相似解决方案