Reverse Words in a String III

Given string s, reverse the letters of each word while preserving whitespace and word order.

Example 1
Input: "Let's take LeetCode contest" → Output: "s'teL ekat edoCteeL tsetno"
Example 2
Input: "Mr Ding" → Output: "rM gniD"

Solution Approach

Split into words, reverse each word individually, join back.

  • Split by space.
  • For each word, reverse it using two pointers or StringBuilder.
  • Join words with space.
Java
class Solution {
    public String reverseWords(String s) {
        String[] words = s.split(" ");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < words.length; i++) {
            sb.append(new StringBuilder(words[i]).reverse());
            if (i < words.length - 1) sb.append(' ');
        }
        return sb.toString();
    }
}
  • Time Complexity: O(N)
  • Space Complexity: O(N)