Skip to content

Latest commit

 

History

History
95 lines (71 loc) · 3.6 KB

151.Reverse_Words_in_a_String(Medium).md

File metadata and controls

95 lines (71 loc) · 3.6 KB

151. Reverse Words in a String (Medium)

Date and Time: Jul 7, 2024, 18:41 (EST)

Link: https://leetcode.com/problems/reverse-words-in-a-string/


Question:

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.


Constraints:

  • $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.


KeyPoints:

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.


Naive Solution:

class Solution:
    def reverseWords(self, s: str) -> str:
        s = s.split()
        s = s[::-1]
        s = " ".join(s)
        return s

Time Complexity: $O(n)$
Space Complexity: $O(1)$


Interview Type Solution:

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: $O(n)$
Space Complexity: $O(n)$


CC BY-NC-SABY: credit must be given to the creatorNC: Only noncommercial uses of the work are permittedSA: Adaptations must be shared under the same terms