DEV Community

Debesh P.
Debesh P.

Posted on

151. Reverse Words in a String | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/reverse-words-in-a-string/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/reverse-words-in-a-string/solutions/7441810/most-optimal-solution-best-for-interview-aub2


leetcode 151


Solution

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();
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)