Reverse Words in a String - LeetCode Solution in C++, Java, Python

1. Introduction

The "Reverse Words in a String" problem involves reversing the order of words in a given string. Each word in the string is separated by spaces, and the goal is to reverse these words while managing any leading, trailing, or multiple spaces between words.

2. Problem

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. Ensure that the returned string has only a single space between words and does not include any extra spaces.

3. Solution in C++

string reverseWords(string s) {
    stringstream ss(s);
    string word, result;
    while (ss >> word) {
        result = word + (result.empty() ? "" : " " + result);
    }
    return result;
}

Explanation:

1. Use a stringstream to split the string s into words.

2. Iterate through each word, appending it to the front of the result string.

3. Ensure that words are separated by a single space.

4. Return the reversed words as a single string.

4. Solution in Java

public String reverseWords(String s) {
    String[] words = s.trim().split("\\s+");
    StringBuilder result = new StringBuilder();
    for (int i = words.length - 1; i >= 0; i--) {
        result.append(words[i]).append(" ");
    }
    return result.toString().trim();
}

Explanation:

1. Trim s to remove leading and trailing spaces, then split it into words using a regular expression to handle multiple spaces.

2. Use a StringBuilder to construct the reversed string.

3. Iterate over the words array in reverse order, appending each word to the StringBuilder.

4. Trim the final string to remove any trailing space and return.

5. Solution in Python

def reverseWords(s):
    return ' '.join(reversed(s.split()))

Explanation:

1. Split s into words using split(), which handles multiple spaces and trims the string.

2. Reverse the list of words using reversed().

3. Join the reversed words into a single string with spaces using ' '.join().


Comments