记录两种思路翻转单词顺序(ssin + 双指针)
作者:
xianhai
,
2021-12-05 10:46:50
,
所有人可见
,
阅读 361
第一种 利用 stringstream ssin(s);
class Solution {
public:
string reverseWords(string s) {
if (s.size() <= 1) {
return s;
}
stringstream ssin(s);
string str;
vector<string> words;
while (ssin >> str) {
words.push_back(str);
}
str = "";
for (int i = words.size() - 1; i >= 0; i--) {
str += words[i] + " ";
}
str = str.substr(0, str.size() - 1);
return str;
}
};
第二种 利用双指针
class Solution {
public:
string reverseWords(string s) {
if (s.size() <= 1) {
return s;
}
vector<string> words;
for (int i = 0, j = 0; i < s.size(); i=++j) {
// 找到单词结尾
while (s[j] != ' ' && j < s.size()) {
j++;
}
// cout << s.substr(i, j - i) << endl;
words.push_back(s.substr(i, j - i));
}
string res;
for (int i = words.size() - 1; i >= 0; i--) {
res += words[i] + " ";
}
return res.substr(0, res.size() - 1);
}
};