LeetCode 题解(262) : Reverse Words in a String II

来源:互联网 发布:局内Windows无法访问 编辑:程序博客网 时间:2024/06/05 11:00

题目:

Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.

The input string does not contain leading or trailing spaces and the words are always separated by a single space.

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

Could you do it in-place without allocating extra space?

Related problem: Rotate Array

题解:

先反转整个string,在反转每个单词。

C++版:

class Solution {public:    void reverseWords(string &s) {        reverse(s.begin(), s.end());        int i = 0;        while(i < s.length()) {            int j = i;            while(j < s.length() && s[j] != ' ')                j++;            for(int k = i; k < i + (j - i) / 2; k++) {                int t = s[k];                s[k] = s[i + j - 1 - k];                s[i + j - 1 - k] = t;            }            i = j + 1;        }    }};

Python版:

class Solution(object):    def reverseWords(self, s):        """        :type s: a list of 1 length strings (List[str])        :rtype: nothing        """        s.reverse()        i = 0        while i < len(s):            j = i            while j < len(s) and s[j] != " ":                j += 1            for k in range(i, i + (j - i) / 2 ):                t = s[k]                s[k] = s[i + j - 1 - k]                s[i + j - 1 - k] = t            i = j + 1

0 0
原创粉丝点击