151. Reverse Words in a String

来源:互联网 发布:js条件公式编辑器 编辑:程序博客网 时间:2024/05/21 17:01

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

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

Update (2015-02-12):
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.

题目要求将一串单词倒置,即单词保持不变,单词的顺序倒过来。如果忽略空间复杂度为O(1),可以直接用栈来做;如果要实现空间复杂度为O(1),则要在原字符串上操作。想法是先把每个单词倒置,然后整个句子倒置。要注意的是空格的问题。字符串的前面可能有空格,单词和单词之间的空格也不一定只有一个,所以要把空格全弄到字符串的后面(单词和单词之间留一个)。则把单词和单词前面的空格一起倒置,如"  abc"变成“cba  " ,然后留一个空格,其后的单词也这样操作。如”  abc   dce“变成”cba ecd    "。最后用resize函数重新定字符串的长和用reverse函数将整个字符串倒置。

代码:
class Solution {public:void reverse(string &s,int l,int r){while(l<r) swap(s[l++],s[r--]);}void reverseWords(string &s){if(s.empty()) return;s+="  ";int n=s.size();int l=0,r=0,flg=0;while(l<n){int wl=0;while(s[r]==' '&&r<n) r++;while(s[r]!=' '&&r<n) { wl++; r++; }if(wl==0) break;reverse(s,l,r-1);l=l+wl+1;r=l;flg=1;}if(flg==0) {s.resize(0);return;}s.resize(l-1);reverse(s,0,l-2);}};


0 0