Skip to content

Commit

Permalink
re-solve "151. Reverse Words in a String"
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Sep 12, 2024
1 parent dc22e6e commit 09c6d43
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 19 deletions.
1 change: 1 addition & 0 deletions .plan
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
Sep 12, 2024

* re-solve "14. Longest Common Prefix"
* re-solve "151. Reverse Words in a String"

Sep 11, 2024

Expand Down
35 changes: 16 additions & 19 deletions src/reverse_words_in_a_string.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,22 @@
class Solution:
def reverseWords(self, s: str) -> str:
result: list[str] = []
from collections.abc import Iterator

word: list[str] = []

for char in s:
if char == " " and word:
result.append("".join(word))
word = []
elif char != " ":
word.append(char)
def iter_words(s: str) -> Iterator[str]:
buffer: list[str] = []

if word:
result.append("".join(word))
for letter in s:
if letter.isspace():
if buffer:
yield "".join(buffer)
buffer.clear()
else:
buffer.append(letter)

left = 0
right = len(result) - 1
if buffer:
yield "".join(buffer)

while left < right:
result[left], result[right] = result[right], result[left]
left += 1
right -= 1

return " ".join(result)
class Solution:
def reverseWords(self, s: str) -> str:
words = list(iter_words(s))
return " ".join(reversed(words))
1 change: 1 addition & 0 deletions tests/test_reverse_words_in_a_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
("the sky is blue", "blue is sky the"),
(" hello world ", "world hello"),
("a good example", "example good a"),
("EPY2giL", "EPY2giL"),
],
)
def test_solution(s, expected):
Expand Down

0 comments on commit 09c6d43

Please sign in to comment.