題目鏈接:https://oj.leetcode.com/problems/reverse-words-in-a-string/
解題思路:以空格爲分隔符提取出每一個單詞後逆序輸出
代碼:
class Solution {
public:
void reverseWords(string &s) {
if (s.empty()) {
return;
}
str_list.clear();
string word;
int offset = 0;
while (offset < s.length()){
findWord(s, offset);
}
s = "";
for (list<string>::const_iterator it = str_list.begin(); it != str_list.end(); it++) {
s.append(*it);
s.append(" ");
}
if (!s.empty()) {
s.erase(s.end() - 1);
}
}
private:
void findWord(string s, int& offset) {
int len = 0;
int i;
for (i = offset; i < s.length(); i++) {
if (s.at(i) == ' ') {
if (len != 0) {
str_list.push_front(s.substr(offset, len));
offset = i + 1;
return;
}
else {
offset++;
continue;
}
}
len++;
}
if (len != 0) {
str_list.push_front(s.substr(offset, len));
}
offset = i + 1;
}
list<string> str_list;
};