Instagram
youtube
Facebook
Twitter

Reverse words in a String Leetcode Solution

In this tutorial, we will solve a leetcode problem, reverse words in a string in python.

Task:

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"

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 <= s.length <= 104
  • s contains English letters (upper-case and lower-case), digits, and spaces ' '.
  • There is at least one word in s.

Solution:

class Solution:
    def reverseWords(self, s: str) -> str:
        lst = s.split()
        lst, s = lst[::-1], ""
        for i in lst:
            s += i
            s += ' '
        return s.strip()

Steps:

step1: First, In this problem, we split the string s and store it into a list last by using .split() function.

step2: Then, reverse the list last and re-declare the string s as empty.

step3: Now, loop through the list lst and add the element into string s with space.

step4: After the loop, we return the string s but also remove any unnecessary white spaces using the function .strip()