Skip to content

Instantly share code, notes, and snippets.

@munguial
Created July 15, 2020 18:13
Show Gist options
  • Save munguial/2d23c9b6be5c8126c8f235c5914ad2fb to your computer and use it in GitHub Desktop.
Save munguial/2d23c9b6be5c8126c8f235c5914ad2fb to your computer and use it in GitHub Desktop.
July - Day 15 - Reverse Words in a String
# https://leetcode.com/explore/challenge/card/july-leetcoding-challenge/546/week-3-july-15th-july-21st/3391/
class Solution:
def reverseWords(self, s: str) -> str:
def reverse(i: int, j: int):
while i < j:
s1[i], s1[j] = s1[j], s1[i]
i += 1
j -= 1
s1 = list(s)
reverse(0, len(s1) - 1)
start = 0
res = []
for i, v in enumerate(s1):
if v != ' ' and (i == 0 or s1[i - 1] == ' '):
start = i
elif v == ' ' and (i > 0 and s1[i - 1] != ' '):
reverse(start, i - 1)
res.append(''.join(s1[start : i]))
if i == len(s1) - 1 and v != ' ':
reverse(start, i)
res.append(''.join(s1[start : i + 1]))
return ' '.join(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment