一看到題目, 直覺就是用 stack 去實作
class Solution {
public:
/*
* @param s: A string
* @return: A string
*/
string reverseWords(string &s) {
// write your code here
stack<string> strStack;
string word;
string::iterator iter;
for (iter = s.begin(); iter != s.end(); iter++) {
if (' ' == *iter) {
if (0 != word.length()) {
strStack.push(word);
word.erase();
}
}
else {
word.push_back(*iter);
}
}
if (0 != word.length()) {
strStack.push(word);
}
string result;
while(! strStack.empty()) {
if (0 != result.length()) {
result.push_back(' ');
}
result.append(strStack.top());
strStack.pop();
}
return result;
}
};
沒有留言:
張貼留言