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;
        }
    }
};

 

转载于:https://www.cnblogs.com/yaoyudadudu/p/9411259.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值