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".


思路:就是对首尾空格和中间连续空格的处理。为了方便处理,在s的首部用insert(迭代器,要插入的值)一个空格。

从后往前来,每次发现一个单词,就逆序放到stack中,然后发现一个空格(该空格的前一个字符不能是空格),就把stack中的值挨个放到string res中。最后清空s,把res赋值给s即可。

代码:

class Solution {
public:
    void reverseWords(string &s) {
        if(s=="") return;
        string res;
        stack<char> temp;
        int i=s.size()-1;
        bool tailspace=true;
        if(s[0]!=' ') s.insert(s.begin(),' ');
        
        while(i>=0){
            if(s[i]==' '&&tailspace){
                --i;
                continue;
            }
            else if(s[i]!=' '){
                tailspace=false;
                temp.push(s[i]);
            }
            else if(s[i]==' '&&!tailspace){
                if(i!=0&&s[i-1]!=' ')
                {
                    while(!temp.empty())
                    {
                        char t=temp.top();
                        temp.pop();
                        res.push_back(t);
                    }
                    res.push_back(' ');
                }else if(i==0){//第一个字符一定是空格
                    while(!temp.empty())
                    {
                        char t=temp.top();
                        temp.pop();
                        res.push_back(t);
                    }
                }
            }
            --i;
        }
        s.clear();
        s=res;
    }
};
原文地址:https://www.cnblogs.com/fightformylife/p/4085696.html