151. Reverse Words in a String

Medium

Problem Description

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.

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.
Jump to Solution: Python Java C++ JavaScript C#

Python Solution


def reverseWords(s: str) -> str:
    # Split string into words and filter out empty strings
    words = [word for word in s.split() if word]
    
    # Reverse the list of words and join with a single space
    return ' '.join(words[::-1])

Java Solution


class Solution {
    public String reverseWords(String s) {
        // Split string into words
        String[] words = s.trim().split("\\s+");
        
        // Reverse the array of words
        StringBuilder result = new StringBuilder();
        for (int i = words.length - 1; i >= 0; i--) {
            result.append(words[i]);
            if (i > 0) {
                result.append(" ");
            }
        }
        
        return result.toString();
    }
}

C++ Solution


class Solution {
public:
    string reverseWords(string s) {
        // Remove leading and trailing spaces
        s = trim(s);
        
        // Reverse the entire string
        reverse(s.begin(), s.end());
        
        // Reverse each word
        int start = 0;
        for (int i = 0; i <= s.length(); i++) {
            if (i == s.length() || s[i] == ' ') {
                reverse(s.begin() + start, s.begin() + i);
                start = i + 1;
            }
        }
        
        // Remove extra spaces
        string result;
        bool space = false;
        for (char c : s) {
            if (c != ' ') {
                result += c;
                space = false;
            } else if (!space) {
                result += ' ';
                space = true;
            }
        }
        
        return result;
    }
    
private:
    string trim(string s) {
        s.erase(0, s.find_first_not_of(" "));
        s.erase(s.find_last_not_of(" ") + 1);
        return s;
    }
};

JavaScript Solution


/**
 * @param {string} s
 * @return {string}
 */
var reverseWords = function(s) {
    // Split string into words, filter out empty strings, and reverse
    return s.trim().split(/\s+/).reverse().join(' ');
};

C# Solution


public class Solution {
    public string ReverseWords(string s) {
        // Split string into words and filter out empty strings
        string[] words = s.Trim().Split(new[] { ' ' }, 
            StringSplitOptions.RemoveEmptyEntries);
        
        // Reverse the array of words
        Array.Reverse(words);
        
        // Join words with a single space
        return string.Join(" ", words);
    }
}

Complexity Analysis

Solution Explanation

This solution uses string manipulation techniques:

Key points: