题目:
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 reverseWord(string s){ if(s.size() == 0) return s; for(int i = 0; i <= (s.size()-1)/2; i++){ char temp = s[i]; s[i] = s[s.size()-1-i]; s[s.size()-1-i] = temp; } return s; } string reverseWords(string s) { vector<string> l; string res; int index = 0; while((index = s.find(" ")) != string::npos){ string t = s.substr(0, index); s = s.substr(index+1); l.push_back(t); } l.push_back(s); for(int i = 0; i < l.size(); i++){ string r = reverseWord(l[i]); if(i == 0) res = r; else res =res + ' ' + r; } return res; } };