当前位置:网站首页>Leetcode151 - invert words in string - String - simulation

Leetcode151 - invert words in string - String - simulation

2022-04-23 14:48:00 Li Fan, hurry up

Original link
 Insert picture description here

Note:

Turn it over first , Then pick out each word , Turn it over and put it in the answer
It seems that you can't open a new one string Operate directly on the original

class Solution {
    
public:
    string reverseWords(string s) {
    
        string ans;
        reverse(s.begin(), s.end());
        int p = 0;
        while(p < s.size()){
    
            string word = "";
            while(s[p] == ' ' && p < s.size())  p ++;
            while(s[p] != ' ' && p < s.size())  word += s[p ++];
            reverse(word.begin(), word.end());
            ans += word;
            ans += ' ';
        }
        ans.pop_back();
        if(ans[ans.size() - 1] == ' ')  ans.pop_back();
        return ans;
    }
};

版权声明
本文为[Li Fan, hurry up]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231447599818.html