LeetCode 557: Reverse Words in a String III

Two PointersString

Problem Description

Explanation:

To solve this problem, we can follow these steps:

  1. Split the given string by spaces to get individual words.
  2. Reverse each word separately.
  3. Join the reversed words back together with spaces in between.

Time complexity: O(n) where n is the length of the input string
Space complexity: O(n)

:

Solutions

class Solution {
    public String reverseWords(String s) {
        String[] words = s.split(" ");
        StringBuilder result = new StringBuilder();
        
        for (String word : words) {
            result.append(new StringBuilder(word).reverse()).append(" ");
        }
        
        return result.toString().trim();
    }
}

Loading editor...