Reverse each word individually in a sentence (preserving word order and spaces).
Input: s="Let's take LeetCode contest" → Output: "s'teL ekat edoCteeL tsetnoc"
Input: s="Mr Ding" → Output: "rM gniD"
Split by spaces, reverse each word, join back.
- Split by spaces
- For each word: reverse it using StringBuilder
- Join all reversed words with spaces
public String reverseWords(String s) {
String[] words = s.split(" ");
StringBuilder sb = new StringBuilder();
for (String w : words) {
if (sb.length() > 0) sb.append(' ');
sb.append(new StringBuilder(w).reverse());
}
return sb.toString();
}
- Time Complexity: O(n)
- Space Complexity: O(n)