LeetCode(151)Reverse Words in a String

题目如下:

Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".


分析如下:

        很基础的题目,需要考虑各种corner cases,比如下列:

1 "            "

        2"a        "

        3"             a        "

        4"             a"

        5"             a                     b        "

        6"             a b       "

        7"             a  b"

        8"a  b      "

        9"             a  b                c d e f                          g      "

我的代码:

// 20ms过大集合
class Solution {
public:
    void reverseWords(string &s) {
        vector<string> vec;
        int len=(int)s.length();
        if(len==0)
            return;
        int i=0;
        int j=len-1;
        while(i!=len&&s[i]==' ')
            i++;
        while(j!=-1&&s[j]==' ')
            j--;
        int k=i;
        while(i<=j){
            k=i;
            while(s[i]!=' '&&i<=j)
                i++;
            vec.push_back(s.substr(k,i-k));
            while(s[i]==' '&&i<=j)
                i++;
        }
        if(vec.empty()){
            s="";
            return;
        }
        reverse(vec.begin(),vec.begin()+vec.size());
        string m=vec[0];
        for(int i=1;i<vec.size();i++){
            m+=" ";
            m+=vec[i];
        }
        s=m;
    }
};

小结扩展:

(1) 之前有道相关的题目,在这篇文章的“小结扩展1“这里


updated-2014-11-16:

class Solution {
public:
    void reverseWords(string &s) {
        // preprocess 1 去空串
        if (s == "")
            return;
        int i = 0;
        // preprocess 2 去全空白串。"        "
        while(i < s.length() && s[i] == ' ')  
            i++;
        if (i == s.length()) {
            s = "";
            return ;
        }
        // start work
        string word;
        istringstream str_stream(s);
        string res = "";
        while(str_stream >> word) {
            //if (word == "")  continue;  // str_stream>>word会挤掉单词之间的所有的空格符,不管是1个还是N个,这句没有必要
            res = " " + word + res;
        }
        s = res.substr(1);
        return;
    }
};
上面的时间复杂度是 2 * o(n),第1个o(n)预处理,第2个o(n)去真正干活。预处理做的主要事情是如果输入字符串全部都是"     ",则不能走入while循环,否则报错。

暂时没有找到什么办法可以在1 * o(n)的时间完成。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值