码迷,mamicode.com
首页 > 其他好文 > 详细

186. Reverse Words in a String II

时间:2017-07-26 23:47:43      阅读:348      评论:0      收藏:0      [点我收藏+]

标签:question   inpu   enumerate   rail   amp   esc   self   ext   ems   

https://leetcode.com/problems/reverse-words-in-a-string-ii/#/description

 

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?

 

 

Sol :

 

class Solution:
    # @param s, a list of 1 length strings, e.g., s = [‘h‘,‘e‘,‘l‘,‘l‘,‘o‘]
    # @return nothing
    def reverseWords(self, s):
        
        # Time O(n) Space O(1)
        # We first reverse every single word and then reverse the string from start to end.
        
        def reverse(i,j):
            while 0 <= i < j < len(s):
                s[i], s[j] = s[j], s[i]
                i, j = i + 1, j - 1
                
        # ex. s = [‘t‘, ‘h‘, ‘e‘, ‘ ‘, ... , ‘b‘, ‘l‘, ‘u‘, ‘e‘]
        s.append(" ")
        start = 0
        for i, v in enumerate(s):
            # reverse chars in every word
            # ex. s = [‘e‘, ‘h‘, ‘t‘, ... , ‘e‘, ‘u‘, ‘l‘, ‘b‘]
            if v == " ":
                reverse(start, i - 1)
                start = i + 1
            
        s.pop()
        # reverse each char in s
        # ex. s = [‘b‘, ‘l‘, ‘u‘, ‘e‘, ... , ‘t‘, ‘h‘, ‘e‘]
        reverse(0, len(s) - 1)
        
            
        

 

 
 
 

186. Reverse Words in a String II

标签:question   inpu   enumerate   rail   amp   esc   self   ext   ems   

原文地址:http://www.cnblogs.com/prmlab/p/7242277.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!