Similar Problems
Similar Problems not available
Reverse Words In A String - Leetcode Solution
LeetCode: Reverse Words In A String Leetcode Solution
Difficulty: Medium
Topics: string two-pointers
Problem description: Given a 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 1: Input: s = "the sky is blue" Output: "blue is sky the"
Example 2: Input: s = " hello world " Output: "world hello" Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3: Input: s = "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.
Solution: We can solve this problem in two steps:
- Reverse the entire string
- Reverse each word in the string
Step 1: Reverse the entire string We can reverse the entire string by first removing any leading or trailing spaces using the strip() method, and then splitting the string into words using the split() method. We can then join the reversed words using a space separator.
Step 2: Reverse each word in the string We can reverse each word in the string by iterating over the words in the reversed string and reversing each word using the slice notation.
Code:
class Solution:
def reverseWords(self, s: str) -> str:
# Step 1: Reverse the entire string
s = s.strip().split()
s = " ".join(reversed(s))
# Step 2: Reverse each word in the string
words = s.split(" ")
for i in range(len(words)):
words[i] = words[i][::-1]
return " ".join(words)
Time Complexity: O(n), where n is the length of the input string s. Space Complexity: O(n), where n is the length of the input string s.
Reverse Words In A String Solution Code
1