Reverse Words in a String II -- LeetCode

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 };

 

posted @ 2016-01-26 14:28  fenshen371  阅读(139)  评论(0编辑  收藏  举报