题目:
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) {
stack<char> tem;
string result;
string s1 = s + ' ';
for (auto c : s1){
if ( c != ' ')
tem.push(c);
else {
while(!tem.empty()){
result = result + tem.top();
tem.pop();
}
result = result + ' ';
}
}
result = result.substr(0, result.length()-1);
return result;
}
};
运行时间:772ms
别人的:
class Solution {
public:
string reverseWords(string s) {
string result(s.length(), 32);
int start = 0;
int end = s.find(32);
while (end != -1) {
for (int i = start; i < end; ++i)
result[end - (i - start) - 1] = s[i];
start = end + 1;
end = s.find(32, start);
}
end = s.length();
for (int i = start; i < end; ++i)
result[end - (i - start) - 1] = s[i];
return result;
}
};
运行时间:26mm
栈比较耗时间?