This problem statement is a part of LeetCode's card Arrays and Strings. Under the sub-heading Conclusion.
Given an input string, reverse the string word by word.
Input: "the sky is blue" Output: "blue is sky the"
Input: " hello world! " Output: "world! hello" Explanation: Your reversed string should not contain leading or trailing spaces.
Input: "a good example" Output: "example good a" Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
- A word is defined as a sequence of non-space characters.
- Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
- You need to reduce multiple spaces between two words to a single space in the reversed string.
- Replace double space with single space.
- Remove leading and trailing spaces.
class Solution: def reverseWords(self, s: str) -> str: s.replace(" ", " ").rstrip().lstrip() string = s.split() string.reverse() return ' '.join(string)
- We have hardcoded 2 spaces. Hardcoding in programming should never be done.
- If count of consecutive spaces is increased. The code would fail.
- Using built-in method reverse() could appear as a shortcut.
- s.lstrip().rstrip().split(). Takes care of multiple spaces, leading spaces, trailing space.
- replace reverse() with implementation of reverse.
class Solution: def reverseWords(self, s: str) -> str: string = s.lstrip().rstrip().split() start = 0 end = len(string) - 1 while start < end: temp = string[start] string[start] = string[end] string[end] = temp start += 1 end -= 1 return ' '.join(string)
Last section of the post. Which starts from learnings from the shortcomings of the above snippet is updated after seeing the first comment.