1、自定义split
我们可以通过自定义一个split函数,将字符串分割成多个字符串构成的数组。而后我们将数组中的内容逆序输出加入到结果的字符串中即可。
class Solution {
public:
vector<string> split(string s, char target) {
int low = 0, high, n = s.size();
vector<string> words;
while (low < n) {
while (s[low] == target) ++low;
if (low >= n) break;
high = low + 1;
while (s[high] != target && high < n) ++high;
words.emplace_back(s.substr(low, high - low));
low = high;
}
return words;
}
string reverseWords(string s) {
string res;
vector<string> words = split(s, ' ');
reverse(words.begin(), words.end());
for (string s: words) {
if (!res.empty()) res += " ";
res += s;
}
return res;
}
};
2、双端队列
我们可以利用一个双端队列来实现字符串的逆序。我们首先去除字符串中的空格,而后将读入的单词加入队列的头部,而后我们不断循环从队列中弹出单词即可。
class Solution {
public:
string reverseWords(string s) {
int left = 0, right = s.size() - 1;
while (left <= right && s[left] == ' ') ++left;
while (left <= right && s[right] == ' ') --right;
deque<string> d;
string word;
while (left <= right) {
char c = s[left];
if (word.size() && c == ' ') {
d.push_front(move(word));
word = "";
}
else if (c != ' ') {
word += c;
}
++left;
}
d.push_front(move(word));
string ans;
while (!d.empty()) {
ans += d.front();
d.pop_front();
if (!d.empty()) ans += ' ';
}
return ans;
}
};