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.
先按空格把每个word分开,再逆转每个word,
class Solution {
public:
string reverseWords(string s) {
string ans = "";
int pos = 0;
int idx = 0;
while((idx = s.find(' ', pos)) != string::npos){
string str = s.substr(pos, idx-pos);
reverse(str.begin(), str.end());
ans += str;
ans += ' ';
pos = idx+1;
}
string str = s.substr(pos);
reverse(str.begin(), str.end());
ans += str;
return ans;
}
};
转载请注明原文地址: https://ju.6miu.com/read-671617.html