151. Reverse Words in a String
Two pointers, String, Two Pointers ·Problem Statement
link: https://leetcode.com/problems/reverse-words-in-a-string/ https://leetcode.cn/problems/reverse-words-in-a-string/
Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
Example:
Input: s = "the sky is blue"
Output: "blue is sky the"
Input: s = " hello world "
Output: "world hello"
Input: s = "a good example"
Output: "example good a"
Solution Approach
The solution uses string manipulation methods to reverse the words while maintaining their order and removing extra spaces.
Algorithm
- Splitting the String: Use Python’s split method, which naturally discards any leading, trailing, or multiple spaces between words and splits the string into words.
- Reversing the Words: Reverse the list of words obtained in the previous step.
- Joining the Words: Join the reversed list of words using a space to form the final reversed string.
Implement
class Solution:
def reverseWords(self, s: str) -> str:
l = s.split()
l.reverse()
return " ".join(l)