Reverse Words in a String II
题目描述
do it in-place, no extra space
解题方法
这里的输入也不同了,是一个list, 这样才可以in-place
Solution
class Solution(object):
def reverseWords(self, s):
"""
:type s: a list of 1 length strings (List[str])
:rtype: nothing
"""
self.reverse(s, 0, len(s) - 1)
first = 0
for i in range(len(s)):
if s[i] == " ":
self.reverse(s, first, i-1)
first = i + 1
elif i == len(s) - 1:
self.reverse(s, first, i)
def reverse(self, s, start, end):
while start < end:
s[start], s[end] = s[end], s[start]
start += 1
end -= 1