leetcode151. 颠倒字符串中的单词

class Solution {
public:
    string reverseWords(string s) {
        stack<string> sk;
        string t="";
        for(int i=0;i<s.size();i++){
            if(s[i]!=' ')t+=s[i];
            else if(t!=""){
                sk.push(t);
                t="";
            }
        }
        if(t!="")sk.push(t);
        string ans=sk.top();
        sk.pop();
        while(!sk.empty()){
            ans+=" "+sk.top();
            sk.pop();
        }
        return ans;
    }
};
class Solution {
public:
    string reverseWords(string s) {
        string ans = "";
        string t="";
        for(int i=0;i<s.size();i++){
            if(s[i]!=' ')t+=s[i];
            else if(t!=""){
                if(ans=="")ans=t;
                else ans=t+" "+ans;
                t="";
            }
        }
        if(t!=""){
            if(ans=="")ans=t;
                else ans=t+" "+ans;
        }
        return ans;
    }
};