HomeLeetcode151. Reverse Words in a String - Leetcode Solutions

151. Reverse Words in a String – Leetcode Solutions

Description

Given an input string s, reverse the order of the words.

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.

Examples:

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 in Python

Python
class Solution:
    def reverseWords(self, s: str) -> str:
        # Step 1: Strip leading and trailing spaces
        stripped_string = s.strip()
        
        # Step 2: Split the string into words based on spaces
        words = stripped_string.split()
        
        # Step 3: Reverse the list of words
        reversed_words = words[::-1]
        
        # Step 4: Join the reversed list of words into a single string with a single space separating the words
        result = ' '.join(reversed_words)
        
        # Step 5: Return the resulting string
        return result

Explanation:

  1. Strip leading and trailing spaces: The strip() method is used to remove any leading and trailing whitespace from the input string. This ensures that there are no extra spaces at the beginning or end of the string.
  2. Split the string into words: The split() method without any arguments splits the string into a list of words based on any whitespace and removes any extra spaces between the words. This ensures that multiple spaces between words are handled correctly.
  3. Reverse the list of words: The list of words is reversed using slicing ([::-1]). This creates a new list with the words in reverse order.
  4. Join the reversed list of words: The join() method is used to concatenate the words in the reversed list into a single string, with a single space ' ' separating each word.
  5. Return the resulting string: The final result is returned.

This approach ensures that the output string has words in reverse order, separated by a single space, without any leading or trailing spaces.

Solution in Javascript

JavaScript
/**
    @param {string} s

    @return {string}
    */
    var reverseWords = function(s) {
    // Step 1: Trim leading and trailing spaces
    s = s.trim();

    // Step 2: Split the string into words based on spaces
    // This will handle multiple spaces as well
    let words = s.split(/\s+/);

    // Step 3: Reverse the array of words
    words.reverse();

    // Step 4: Join the reversed words array into a single string with a single space separating the words
    let result = words.join(' ');

    // Step 5: Return the resulting string
    return result;
    };

Solution in Java

Java
class Solution {
    public String reverseWords(String s) {
        // Step 1: Trim leading and trailing spaces
        s = s.trim();
        
        // Step 2: Split the string into words based on spaces
        // This will handle multiple spaces as well
        String[] words = s.split("\\s+");
        
        // Step 3: Initialize a StringBuilder to hold the reversed words
        StringBuilder reversed = new StringBuilder();
        
        // Step 4: Iterate over the array of words in reverse order
        for (int i = words.length - 1; i >= 0; i--) {
            reversed.append(words[i]);
            if (i > 0) {
                reversed.append(" ");
            }
        }
        
        // Step 5: Convert StringBuilder to String and return the result
        return reversed.toString();
    }
}

Solution in C#

C#
public class Solution {
    public string ReverseWords(string s) {
        // Step 1: Trim leading and trailing spaces
        s = s.Trim();
        
        // Step 2: Split the string into words based on spaces
        // This will handle multiple spaces as well
        string[] words = s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        
        // Step 3: Reverse the array of words
        Array.Reverse(words);
        
        // Step 4: Join the reversed words array into a single string with a single space separating the words
        string result = string.Join(" ", words);
        
        // Step 5: Return the resulting string
        return result;
    }
}

Subscribe
Notify of

0 Comments
Inline Feedbacks
View all comments

Popular