zoukankan      html  css  js  c++  java
  • 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.

    解题思路:

    我想的办法使用getline读入字符串并以‘ ’作为分隔符,需要检查当前获取字符串是否为空。

    空间复杂度不为O(1),所以我就折叠一下:)

    来看看空间复杂度为1的解法(来自于Grandyang):

    使用reverse()翻转字符串,然后再单独翻转单词。

    使用了辅助变量StoreIndex来记录新的字符串中单词的开始

    初始值为0。

    找到第一个不为空的字符后,将其拷贝到storeIndex的位置,然后用reverse再翻转单词。

    为了防止出现“    ”开始的情况,用了resize。

    代码:

    class Solution {
    public:
        void reverseWords(string &s) {
            vector<string> v;
            stringstream ss(s);
            string temp;
            while(getline(ss, temp, ' ')){
                if(temp.size() != 0)
                    v.push_back(temp);
            }
            s.clear();
            for(int i = v.size() - 1; i > -1; i--){
                s += v[i] + " ";
            }
            s = s.substr(0, s.size() - 1);
        }
    };
    空间复杂度不为O(1)

    空间复杂度为O(1) :

    class Solution {
    public:
        void reverseWords(string &s) {
            int storeIdx = 0, n = s.size();
            reverse(s.begin(), s.end());
            for(int i = 0; i < n; i++ ){
                if(s[i] != ' '){
                    if(storeIdx != 0)
                        s[storeIdx++] = ' ';
                    int j = i;
                    while(j < n && s[j] != ' ')
                        s[storeIdx++] = s[j++];
                    reverse(s.begin()+storeIdx - (j-i), s.begin() + storeIdx);
                    i = j;
                }
            }
            s.resize(storeIdx);
        }
    };
  • 相关阅读:
    Problem: 八中上厕所
    Problem: 最短路上的统计
    股票买卖问题
    Redis(十二)——Redis为什么是单线程的?
    链表题汇总
    Redis(十一)——集群模式
    Redis(十)——哨兵模式
    Redis(九)——主从复制
    Redis(八)——客户端与服务器
    Redis(七)——事件
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9187000.html
Copyright © 2011-2022 走看看