【LeetCode】Reverse Words in a String

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

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

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.

class Solution {
public:
    void reverse(string &s, int i, int j)
    {
        while(i<j)
        {
            char tmp = s[j];
            s[j--] = s[i];
            s[i++] = tmp;
        }
    }
    void reverseWords(string &s) 
    {
        int i = 0, k = 0, j = 0;
        while(s[i] == ' ') i++;
        
        for(; i < s.size(); i++)
        {
            if(!(s[i] == ' '&&s[i] == s[i-1]))
                s[k++] = s[i];
        }
        while(s[k-1] == ' ')
            k--;
        s.resize(k);
        reverse(s,0,k-1);
        i = 0;
        while(j < k)
        {
            while(s[j]!=' '&& j < k)
                j++;
            reverse(s,i,j-1);
            i = ++j;
        }
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章