186. Reverse Words in a String II

问题描述:

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

Example:

Input:  ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]

Note: 

  • A word is defined as a sequence of non-space characters.
  • The input string does not contain leading or trailing spaces.
  • The words are always separated by a single space.

Follow up: Could you do it in-place without allocating extra space?

 

解题思路:

很容易想到用栈来解答。

corner cases: 输入字符串为空,则直接返回,不作处理

当遇到非空字符时,向栈中加入;遇到空字符串时,将栈中内容全部弹出并依次加入到数组尾部。

最后使用reverse反转整个返回字符串。

 

follow up:

  直接在原数组上进行操作

  

 

代码:

class Solution {
public:
    void reverseWords(vector<char>& str) {
        vector<char> tmp;
        stack<char> stk;
        for(auto c : str){
            if(c == ' '){
                while(!stk.empty()){
                    tmp.push_back(stk.top());
                    stk.pop();
                }
                tmp.push_back(c);
            }else{
                stk.push(c);
            }
        }
        while(!stk.empty()){
            tmp.push_back(stk.top());
            stk.pop();
        }
        reverse(tmp.begin(), tmp.end());
        str = tmp;
    }
};

follow up:

class Solution {
public:
    void reverseWords(vector<char>& s) {
        reverse(s.begin(), s.end());
        int n = s.size(), l = 0, r = 0;
        while (r < n) {
            while (r < n && !isspace(s[r])) r++;
            reverse(s.begin() + l, s.begin() + r); 
            l = ++r;
        }
    }
};

 

posted @ 2018-08-03 07:24  妖域大都督  阅读(106)  评论(0编辑  收藏  举报