Skip to main content

Command Palette

Search for a command to run...

Reverse Words in a String

Updated
•3 min read•View as Markdown
J

💡 Passionate about Core Java, currently diving deep into Data Structures & Algorithms and Advanced Java. Always eager to learn and share knowledge. 🚀

Introduction

Today marks the beginning of my journey of writing daily blogs about the things I learn. I kickstart this journey with a LeetCode problem that I solved today: Reverse Words in a String. This problem is a classic example of string manipulation in programming, and it comes with some interesting challenges related to handling whitespace. Let's dive into the problem statement, approach, and solution in detail.

Problem Statement

The problem requires reversing the order of words in a given string. A word is defined as a sequence of non-space characters. The input string can contain leading or trailing spaces and multiple spaces between words. The solution must return a string where the words appear in reverse order, with only a single space separating each word and no leading or trailing spaces.

Example:

Input: " the sky is blue " Output: "blue is sky the"

Approach to Solve the Problem

To solve this problem, we need to handle several key aspects:

  1. Trim Leading and Trailing Spaces: Remove any extra spaces at the beginning or end of the string.

  2. Reduce Multiple Spaces Between Words: Replace sequences of multiple spaces with a single space.

  3. Reverse the Order of Words: Split the string into words, reverse the order, and join them back into a single string with spaces in between.

Solution

Here's the Java code that accomplishes the above tasks:

private static String reverse(String s) {
    s = s.trim();
    s = s.replaceAll("\\s+"," ");

    String [] arr = s.split(" ");
    String ans = "";

    for(int i = arr.length-1; i>=0; i--){
        ans += arr[i] + " ";
    }

    return ans.substring(0,ans.length()-1);
}

Explanation

  1. Trimming Spaces: The trim() method removes leading and trailing spaces from the string.

  2. Replacing Multiple Spaces: The replaceAll("\\s+", " ") method uses a regular expression to replace sequences of one or more whitespace characters with a single space.

  3. Splitting the String: The split(" ") method splits the string into an array of words based on spaces.

  4. Reversing the Words: A for-loop iterates over the array from the last element to the first, building the result string in reverse order.

  5. Removing Trailing Space: The substring(0, ans.length() - 1) method removes the extra space added at the end of the result string during the loop.

Conclusion

This solution efficiently handles the problem's requirements, ensuring that the resulting string has words in reverse order, with single spaces separating them, and no leading or trailing spaces. String manipulation problems like these are fundamental in programming and help build a strong foundation for tackling more complex challenges.

I hope you found this explanation helpful. Stay tuned for more daily blogs on interesting problems and concepts I encounter in my learning journey!