Reverse words in a given string

Given a string s, reverse the order of words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Input-Output 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.

Approach

  1. Trim the String: Remove leading and trailing spaces.
  2. Split the String: Split the string into words by spaces.
  3. Reverse the Words: Reverse the list of words.
  4. Join the Words: Join the reversed list of words with a single space.

C++ Program to reverse words in a given string

cpp
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;

// Function to reverse words in a given string
string reverseWords(string s) {
    // Trim leading and trailing spaces
    int start = 0, end = s.size() - 1;
    while (start <= end && s[start] == ' ') start++;
    while (end >= start && s[end] == ' ') end--;
    
    // Split the string into words
    vector<string> words;
    string word;
    for (int i = start; i <= end; i++) {
        if (s[i] == ' ' && !word.empty()) {
            words.push_back(word);
            word = "";
        } else if (s[i] != ' ') {
            word += s[i];
        }
    }
    if (!word.empty()) words.push_back(word);
    
    // Reverse the list of words
    reverse(words.begin(), words.end());
    
    // Join the words with a single space
    stringstream result;
    for (int i = 0; i < words.size(); i++) {
        if (i != 0) result << " ";
        result << words[i];
    }
    
    return result.str();
}

int main() {
    string s = "the sky is blue";
    string result = reverseWords(s);
    cout << "Reversed string: \"" << result << "\"" << endl;
    return 0;
}

Java Program to reverse words in a given string

java

import java.util.*;

public class ReverseWords {
    public static void main(String[] args) {
        String s = "the sky is blue";
        String result = reverseWords(s);
        System.out.println("Reversed string: \"" + result + "\"");
    }

    // Function to reverse words in a given string
    public static String reverseWords(String s) {
        // Trim leading and trailing spaces
        s = s.trim();
        
        // Split the string into words
        List<String> words = new ArrayList<>(Arrays.asList(s.split("\\s+")));
        
        // Reverse the list of words
        Collections.reverse(words);
        
        // Join the words with a single space
        return String.join(" ", words);
    }
}

Python Program to reverse words in a given string

python
def reverseWords(s: str) -> str:
    # Trim leading and trailing spaces
    s = s.strip()
    
    # Split the string into words
    words = s.split()
    
    # Reverse the list of words
    words.reverse()
    
    # Join the words with a single space
    return ' '.join(words)

if __name__ == "__main__":
    s = "the sky is blue"
    result = reverseWords(s)
    print(f"Reversed string: \"{result}\"")

DSA

4087

416

Related Articles