首页 > 代码库 > leetcode-Reverse Words in a String

leetcode-Reverse Words in a String

Reverse Words in a String

 Total Accepted: 15012 Total Submissions: 108513My Submissions

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

click to show clarification.

Have you been asked this question in an interview? 


此题要翻转一个字符串中的单词,属于比较简单的字符串处理题。

C++:
直接扫描字符串把遇到的单词插入到deque的前面,扫描完把deque容器内的单词拼起来即可。
class Solution {
public:
    void reverseWords(string &s) {
        deque<string> ds;
        int b, i(0), len(s.size());
        while (i < len) {
            while (i<len && s[i]==' ') ++i;
            if (i == len) break;
            b = i;
            while (i<len && s[i]!=' ') ++i;
            ds.push_front(s.substr(b, i-b));
        }
        s = "";
        if (ds.empty()) return;
        s += ds[0];
        for (i=1; i<ds.size(); ++i) s += " " + ds[i];
        
    }
};
但是如果加上限制呢?比如不能利用额外线性空间复杂度,又该如何解呢?暂时还没想到。

Python:
Python处理更简单了,三行代码就搞定了。

class Solution:
    # @param s, a string
    # @return a string
    def reverseWords(self, s):
        ss = s.split()
        ss.reverse()
        return " ".join(ss)