leetcode-Reverse Words in a String

Posted mthoutai

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)
        

















以上是关于leetcode-Reverse Words in a String的主要内容,如果未能解决你的问题,请参考以下文章

leetcode-Reverse Words in a String-151

LeetCode-Reverse Bits

LeetCode-Reverse Vowels of a String

LeetcodeReverse Words in a String

Reverse Words in a string

186. Reverse Words in a String II