Reverse Words in a String III(#557)
Category: String, Two Pointer
๐งฉ Problem Statement
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
๐ Examples
Input: s = "Mr Ding"
Output: "rM gniD"
Input: s = "Hello World"
Output: "olleH dlroW"
Input: s = "a b c"
Output: "a b c"
๐ง Approach
To reverse each word in a string while maintaining word order:
โข **Split** the input string by spaces to get all the individual words.
โข For each word, **reverse the characters** using a helper function that uses the two-pointer technique.
โข In the helper function, convert the word to an array of characters, swap characters from both ends moving toward the center, then rejoin them.
โข Finally, **join all reversed words** back into a single string with spaces.
This method ensures in-place reversal of each word without disturbing the original word order.
๐ป Code
var reverseWords = function(s) {
let chars = s.split(" ");
for (let i = 0; i < chars.length; i++) {
chars[i] = reverseWord(chars[i]);
}
return chars.join(" ");
};
function reverseWord(word) {
let start = 0, end = word.length - 1;
let chars = word.split("");
while (start < end) {
[chars[start], chars[end]] = [chars[end], chars[start]];
start++;
end--;
}
return chars.join("");
}
๐ Complexity
Time: O(n)
Space: O(n)