Conventional practice:
Traverse one by one and then splice
class Solution {
public:
string reverseWords(string s) {
string res, tmp;
for (auto c : s) {
if (c != ' ') {
tmp += c;
continue;
}
if (tmp.size()) {
res = tmp + " " + res;
tmp.clear();
}
}
if (tmp.size()) {
res = tmp + " " + res;
tmp.clear();
}
return res.substr(0, res.size() - 1);
}
};
Double pointer:
The above method, because the characters are spliced one by one, the efficiency is lower, in fact, you can select the first position of the string and splice it at once.
class Solution {
public:
string reverseWords(string s) {
s.erase(0, s.find_first_not_of(" "));
s.erase(s.find_last_not_of(" ") + 1);
if (!s.size()) return s;
int i = s.size() - 1;
int j = i;
string res;
while (i >= 0) {
while (i >= 0 && s[i] != ' ') --i;
res += s.substr(i + 1, j - i) + ' ';
while (i >= 0 && s[i] == ' ') --i;
j = i;
}
return res.substr(0, res.size() - 1);
}
};