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)
时间: 2024-10-03 17:28:40