151. Reverse Words in a String

Dare2Solve

Dare2Solve

151. Reverse Words in a String
SAMSUNG 49-Inch Odyssey G9
SAMSUNG 49-Inch Odyssey G9
Because earth is not flat

Intuition

The problem requires reversing the order of words in a given string while ensuring that there is exactly one space separating each word in the output. We must handle cases with leading, trailing, and multiple spaces between words. The key intuition here is to split the string into words, reverse the order of these words, and join them back together with single spaces.

Approach

  1. Splitting the String into Words:

    • Use Python's split() method, which by default splits the string by whitespace and removes extra spaces. This will handle leading, trailing, and multiple spaces between words.
  2. Reversing the Words:

    • Reverse the list of words obtained from the split operation using Python's list reverse() method or slicing.
  3. Joining the Words Back into a String:

    • Use the join() method to concatenate the reversed list of words into a single string with spaces between them.

Complexity

Time Complexity:

O(n), where n is the length of the input string s. This accounts for the time required to split the string, reverse the list of words, and join them back together.

Space Complexity:

O(n), where n is the length of the input string s. This is due to the space required to store the list of words and the final reversed string.

By following this approach, we ensure that the solution is efficient and meets the problem requirements.

Code

C++

#include <string>
#include <vector>
#include <sstream>
using namespace std;
class Solution {
public:
    string reverseWords(string s) {
        vector<string> words;
        stringstream ss(s);
        string word;
        while (ss >> word) {
            words.push_back(word);
        }
        reverse(words.begin(), words.end());
        string result;
        for (int i = 0; i < words.size(); ++i) {
            result += words[i];
            if (i != words.size() - 1) {
                result += " ";
            }}
        return result;
    }};

Python

class Solution:
    def reverseWords(self, s: str) -> str:
        words = s.split()
        words.reverse()
        return ' '.join(words)

Java

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

JavaScript

/**
 * @param {string} s
 * @return {string}
 */
var reverseWords = function(s) {
    s = s.split(' ');
    let res = [];
    for(let i=s.length-1; i>=0; i--) {
        if(s[i]!='') res.push(s[i]);
    }
    return res.join(' ');
};