[LeetCode] Reverse Words in a String

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".

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

解题思路:

1、若用C#实现,非常简单,用字符串的split函数,将非空的子串倒着连接起来即可。

2、C++似乎没有split函数,需要我们自己实现一下,返回vector<string>类型。但是这样需要扫描两次字符串。

3、可以只扫描一次字符串。下面是代码。有几个特殊情况需要考虑(1)可能会有多个空格符(2)可能没有空格符

class Solution {
public:
    void reverseWords(string &s) {
        string result="";
        int len = s.length();
        string word="";
        for(int i=0; i<len; i++){
            if(s[i]!=' '){
                word += s[i];
            }else{
                if(word!=""){
                    if(result!=""){
                        word += " ";
                    }
                    result = word + result;
                    word="";
                }
            }
        }
        if(word!=""){   //这里不要忘了
            if(result!=""){
                word += " ";
            }
            result = word + result;
        }
        s=result;
    }
};


0 条评论

    发表评论

    电子邮件地址不会被公开。 必填项已用 * 标注