Reverse Words in a String III
Problem
Given a string s, reverse the order of characters in each word while still preserving whitespace and the initial word order.
s = "Let's take LeetCode contest""s'teL ekat edoCteeL tsetnoc"def reverse_words(s):
return ' '.join(word[::-1] for word in s.split(' '))
function reverseWords(s) {
const arr = s.split('');
let i = 0;
while (i < arr.length) {
let j = i;
while (j < arr.length && arr[j] !== ' ') j++;
let l = i, r = j - 1;
while (l < r) { [arr[l], arr[r]] = [arr[r], arr[l]]; l++; r--; }
i = j + 1;
}
return arr.join('');
}
class Solution {
public String reverseWords(String s) {
char[] arr = s.toCharArray();
int i = 0;
while (i < arr.length) {
int j = i;
while (j < arr.length && arr[j] != ' ') j++;
int l = i, r = j - 1;
while (l < r) { char t = arr[l]; arr[l] = arr[r]; arr[r] = t; l++; r--; }
i = j + 1;
}
return new String(arr);
}
}
string reverseWords(string s) {
int i = 0, n = s.size();
while (i < n) {
int j = i;
while (j < n && s[j] != ' ') j++;
int l = i, r = j - 1;
while (l < r) swap(s[l++], s[r--]);
i = j + 1;
}
return s;
}
Explanation
Here we keep the words in their places but flip the letters inside each word. The clean way is to walk the string, find one word at a time, and reverse just that stretch of characters in place.
The Python version says it in one line: s.split(' ') breaks the sentence into words, word[::-1] reverses each word, and ' '.join(...) glues them back with the same single spaces. Splitting on a single space keeps the spacing identical to the original.
The other languages do the same idea by hand using two pointers per word: a left pointer l at the word's start and a right pointer r at its end, swapping and stepping inward until they meet. A scanner finds each word's boundaries by stopping at the next space.
Example: "Let's take LeetCode contest". Reverse Let's to s'teL, take to ekat, LeetCode to edoCteeL, contest to tsetnoc. The words stay in order, so the result is "s'teL ekat edoCteeL tsetnoc".
Every character is touched a constant number of times, so this is a single linear pass over the sentence.