Reverse Words in a String III
Problem
Given a string s
, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Constraints
1 <= s.length <= 5 * 104
s
contains printable ASCII characters.s
does not contain any leading or trailing spaces.- There is at least one word in
s
. - All the words in
s
are separated by a single space.
Solution
The problem Reverse Words in a String III
can be solved by finding words separated by whitespaces and reversing each of them.
Implementation
class Solution
{
public:
string reverseWords(string s)
{
s += ' ';
int left = 0;
for (int right = 0; right < s.length(); right++)
if (s[right] == ' ')
{
reverse(s.begin() + left, s.begin() + right);
left = right + 1;
}
s.pop_back();
return s;
}
};