Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
还在探索更好的办法。class Solution {
public:
string reverseWords(string s) {
int n = s.length() - 1;
int start = 0;
int end = start + 1;
while (s[start] != ' ' && start <= n) {
while (s[end] != ' ' && end <= n) {
end++;
}
reverse(s, start, end - 1);
start = end + 1;
end = start + 1;
}
return s;
}
void reverse(string& s, int left, int right) {
while (left < right) {
char c = s[left];
s[left] = s[right];
s[right] = c;
left++;
right--;
}
}
};