From 09c6d4352b79e04ade2ab9da1d976c9c83f9f23f Mon Sep 17 00:00:00 2001 From: Pavel Karateev Date: Thu, 12 Sep 2024 23:42:20 +0200 Subject: [PATCH] re-solve "151. Reverse Words in a String" --- .plan | 1 + src/reverse_words_in_a_string.py | 35 +++++++++++-------------- tests/test_reverse_words_in_a_string.py | 1 + 3 files changed, 18 insertions(+), 19 deletions(-) diff --git a/.plan b/.plan index 2618bd2..0ed2c18 100644 --- a/.plan +++ b/.plan @@ -1,6 +1,7 @@ Sep 12, 2024 * re-solve "14. Longest Common Prefix" +* re-solve "151. Reverse Words in a String" Sep 11, 2024 diff --git a/src/reverse_words_in_a_string.py b/src/reverse_words_in_a_string.py index c2d6579..0c33ccb 100644 --- a/src/reverse_words_in_a_string.py +++ b/src/reverse_words_in_a_string.py @@ -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)) diff --git a/tests/test_reverse_words_in_a_string.py b/tests/test_reverse_words_in_a_string.py index f4ad60e..0ba0f54 100644 --- a/tests/test_reverse_words_in_a_string.py +++ b/tests/test_reverse_words_in_a_string.py @@ -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):