Loading

【leetcode】151. Reverse Words in a String

  Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space. Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
  
class Solution {
public:
    string reverseWords(string s) {
        //包含stack string 字串等操作 “” const char * 原型
        stack<string> dp;
        string res;
        string tmp;
        for(auto ss:s){
            if(ss==' '){
                if(tmp.size()>0) dp.push(tmp);
                tmp="";
            }
            else{
                tmp.push_back(ss);
            }
        }
        if(tmp.size()>0) dp.push(tmp);
        
        while(!dp.empty()){
            res=res+dp.top()+" ";
            dp.pop();
        }
        int len=res.size();
        return res.substr(0,len-1);  
    }
};

  

  getline 写法:
class Solution {
     public:
    string reverseWords(string s) {
        reverse(s.begin(), s.end());
        
       stringstream str(s);
        string token;
        string ans;
        while(getline(str, token, ' ')){
            if(token.empty()) continue;
            reverse(token.begin(), token.end());
            
            ans+= token+' '; 
        }
        
        ans.pop_back();
        
        return ans;
        
    }
};

 

 
posted @ 2021-11-20 14:33  aalanwyr  阅读(17)  评论(0编辑  收藏  举报