Reverse Words in a String II
Problem: Reverse Words in a String II
The difference between this problem and previous one is that the input of this problem is an array of characters. If we simply reverse all characters, letters in a word will be reversed too, which means, we need to fetch every word and reverse them first.
Code in Python:
class Solution(object):
def reverseWords(self, s):
"""
:type s: a list of 1 length strings (List[str])
:rtype: nothing
"""
def reverseWord(l, r):
while l < r:
s[l], s[r] = s[r], s[l]
l += 1
r -= 1
i = 0
for j in xrange(1, len(s)):
if s[j] == " ":
reverseWord(i, j-1)
i = j+1
reverseWord(i, len(s)-1)
reverseWord(0, len(s)-1)