Given string s, reverse the letters of each word while preserving whitespace and word order.
Input: "Let's take LeetCode contest" → Output: "s'teL ekat edoCteeL tsetno"Input: "Mr Ding" → Output: "rM gniD"
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.
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)