557. Reverse Words in a String III
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.
方法1: two pointers
class Solution {
public:
string reverseWords(string s) {
int begin = -1, n = s.size();
for (int end = 0; end < n; end++) {
if (begin == -1) {
if (s[end] != ' ') begin = end;
}
if (end == n - 1 || s[end + 1] == ' ') {
reverse(s.begin() + begin, s.begin() + end + 1);
begin = -1;
}
}
return s;
}
};