LeetCode 151: Reverse Words in a String Solution

Master LeetCode problem 151 (Reverse Words in a String), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

151. Reverse Words in a String

Problem Explanation

Explanation:

To solve this problem, we can follow these steps:

  1. Trim the input string to remove leading and trailing spaces.
  2. Split the input string by spaces to extract individual words.
  3. Reverse the list of words.
  4. Join the reversed words with a single space to form the final result string.

Time complexity analysis:

  • Splitting the string into words takes O(n) time, where n is the length of the input string.
  • Reversing the list of words takes O(n) time.
  • Joining the words back into a string takes O(n) time. Hence, the overall time complexity of this approach is O(n).

Space complexity analysis:

  • The space complexity is O(n) where n is the length of the input string, as we are storing the split words in a list.

:

Solution Code

class Solution {
    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]);
            if (i > 0) {
                result.append(" ");
            }
        }

        return result.toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 151 (Reverse Words in a String)?

This page provides optimized solutions for LeetCode problem 151 (Reverse Words in a String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 151 (Reverse Words in a String)?

The time complexity for LeetCode 151 (Reverse Words in a String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 151 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 151 in Java, C++, or Python.

Back to LeetCode Solutions