翻转字符串(坑比较多)

Given an input string, reverse the string word by word.

 

Example 1:

Input: "the sky is blue"
Output: "blue is sky the"

Example 2:

Input: "  hello world!  "
Output: "world! hello"
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:

Input: "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

class Solution {
public:
    //去掉多余的空格
     string reverseWords(string s) {
        int i=0;
        while(s[i] == ' ') s.erase(s.begin());
        reverse(s.begin(),s.end());
        i=0;
        while(s[i] == ' ') s.erase(s.begin());
        //翻转
        int j=0;
        cout<<s<<endl;
        for(i=0;i<s.size();i++){
            if(s[i] == ' '){
                reverse(s.begin()+j,s.begin()+i);
                i++;
                while(s[i] == ' ')  s.erase(s.begin()+i);
                j = i;
            }
        }
        //最后一个  reverse第二个参数是翻转的位置的后一个位置,所以单独考虑
        reverse(s.begin()+j,s.end());
        return s;
    }

  

posted on 2020-09-06 18:23  wsw_seu  阅读(156)  评论(0编辑  收藏  举报

导航