当前位置:网站首页>leetcode. 151. flip the words in the string

leetcode. 151. flip the words in the string

2022-06-13 01:03:00 Didi dada

  1. Flip the words in the string

Give you a string s , Flip all in the string one by one word .
A word is a string of non whitespace characters .s Use in At least A space in the string Word separation .
Please return to a flip s Chinese word order and use Single space Connected strings .

explain :

Input string s It can be in the front 、 Contain extra spaces after or between words .
After turning over, the words should be Separate with only one space .
In the flipped string Should not contain extra spaces .

Example 1:

Input :s = “the sky is blue”
Output :“blue is sky the”

Example 2:

Input :s = " hello world "
Output :“world hello”
explain : The input string can contain extra spaces before or after , However, the flipped characters cannot include .

Example 3:

Input :s = “a good example”
Output :“example good a”
explain : If there are extra spaces between two words , Reduce the space between words after flipping to only contain one .

Example 4:

Input :s = " Bob Loves Alice "
Output :“Alice Loves Bob”

Example 5:

Input :s = “Alice does not even like bob”
Output :“bob like even not does Alice”

  1. C++
class Solution {
    
public:
    string reverseWords(string s) {
    
        vector<string> tmp;
        int n = s.size();
        string word;
        for(int i=0;i<n;i++){
    
            if(s[i]==' '){
    
                if(word.size()!=0){
    
                    tmp.emplace_back(word);
                    word = "";
                }
            }
            else
                word+=s[i];
        }
        if(word.size())
            tmp.emplace_back(word);
        reverse(tmp.begin(),tmp.end());
        string res;
        for(auto it=tmp.begin();it!=tmp.end();it++){
    
            res+=*it;
            res+=' ';
        }
        res.pop_back();
        return res;
    }
};
  • Note that there are spaces in the beginning and two consecutive spaces .
  1. python
class Solution:
    def reverseWords(self, s: str) -> str:
        s = s.strip()
        sequence = s.split(' ')
        sequence.reverse()
        res = ''
        for it in sequence:
            if it!='':
                res+=it
                res+=' '
        return res[:-1]
  • Pay attention to the case of continuous spaces ( When consecutive spaces exist split() The function will leave some spaces )
原网站

版权声明
本文为[Didi dada]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280556566622.html