Date and Time: Jul 7, 2024, 18:41 (EST)
Link: https://leetcode.com/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 1:
Input: s = "the sky is blue"
Output: "blue is sky the"
Explanation:
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.
-
$1 <= \text{s.length} <= 10^4$ -
s
contains English letters (upper-case and lower-case), digits, and spaces' '
. -
There is at least one word in s.
Again, it is easy to use built-in functions in Python. But we should also consider the non built-in functions version.
I start from backward, while there is space, we just decrement r
, if s[r]
is not space, we add the character into a temporary variable curr
and after we finish one word, we reverse curr
by [::-1]
and add it to res
with a space before reversed curr
.
Lastly, we need to check if curr
is not empty we append the word to res
, otherwise in Example 2 we will add an extra space to the end. And we just return res[:len(res)-1]
because the last element is space.
class Solution:
def reverseWords(self, s: str) -> str:
s = s.split()
s = s[::-1]
s = " ".join(s)
return s
Time Complexity:
Space Complexity:
class Solution:
def reverseWords(self, s: str) -> str:
r, res = len(s) - 1, ""
while r >= 0:
curr = ""
while r >= 0 and s[r] == " ":
r -= 1
while r >= 0 and s[r] != " ":
curr += s[r]
r -= 1
if curr:
res += (curr[::-1] + " ")
return res[:len(res)-1]
Time Complexity:
Space Complexity: