186. Reverse Words in a String II (Medium)

Description:

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

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

Example

Example1

Input: s = "the sky is blue"
Output: "blue is sky the"

Example2

Input: "a b c"
Output: "c b a"

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


Solution:

NOTE: 为了最后一个单词也会翻转,enumerate(string + [" "]), not enumerate(string + " ") or enumerate(string)

class Solution:
    """
    @param str: a string
    @return: return a string
    """
    def reverseWords(self, string):
        # write your code here
        string = list(string[::-1])
        l = 0
        
        def helper(l,r):
            for i in range(l,(l+r)//2):
                string[i],string[r-1-i+l] = string[r-1-i+l],string[i]
        
        for r,s in enumerate(string + [" "]):
            if s == " ":
                if r == l:
                    l += 1
                else:
                    helper(l,r)
                    l = r+1
                    
        return "".join(string)

Total runtime 101 ms
Your submission beats 91.88% Submissions!

你可能感兴趣的:(186. Reverse Words in a String II (Medium))