zoukankan      html  css  js  c++  java
  • 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;
            }
        }
    };
  • 相关阅读:
    Jsp 4—— 内置对象
    Jsp 3—— 声明语法
    Jsp 2—— 小脚本
    CF1479B1 Painting the Array I
    P5337 [TJOI2019]甲苯先生的字符串
    CF19C Deletion of Repeats
    CF484D Kindergarten
    CF529B Group Photo 2 (online mirror version)
    CF1068B LCM
    CF554A Kyoya and Photobooks
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9411259.html
Copyright © 2011-2022 走看看