Leetcode 151. Reverse Words in a String反转字符串,去除空格

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

Example:  

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

Note:

  • A word is defined as a sequence of non-space characters.
  • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
  • You need to reduce multiple spaces between two words to a single space in the reversed string.

Follow up: For C programmers, try to solve it in-place in O(1) space.

题目链接:https://leetcode.com/problems/reverse-words-in-a-string/

class Solution {
public:
    void reverseWords(string &s) {
     int n=s.size();
        string str="";
        stack<string> stk;
        for(int i=0;i<n;)
        {
            if(s[i]!=' ')
            {
                str+=s[i];
                i++;
            }
            else{
                if(str.size()>0)
                    stk.push(str);
                str="";
                while(s[i]==' ')
                {
                    i++;
                }
            }
        }
        if(str.size()>0)
        stk.push(str);
        s="";
        while(!stk.empty())
        {
            s+=stk.top();
            stk.pop();
            if(!stk.empty())
                s+=" ";
        }
    }
};

猜你喜欢

转载自blog.csdn.net/salmonwilliam/article/details/87893236