Problem : https://leetcode.com/problems/reverse-words-in-a-string-ii/
This problem requests reverse words in place.
So we reverse the entire list first, then reverse every words again.
class Solution:
def reverseWords(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
def reverse(left, right):
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
reverse(0, len(s) - 1)
left = 0
for right in range(len(s)):
if s[right] == ' ':
reverse(left, right -1)
left = right + 1
# revese the last word
reverse(left, len(s) -1)
No comments:
Post a Comment