AcWing 77. 双指针
原题链接
中等
作者:
史一帆
,
2021-04-29 15:39:21
,
所有人可见
,
阅读 286
算法1
class Solution {
public:
string reverseWords(string s) {
if (!s.size()) return ""; // 特判
vector<string> words; // 存单词
for (int i = 0, j = 0; i < s.size(); i = ++ j) // i为快指针,j为慢指针,i = ++ j是为了跳出空格,找到下一个单词
{
while (s[j] != ' ' && j < s.size()) j ++ ; // 找到单词结尾
words.push_back(s.substr(i, j - i)); // 将单词存入vector
}
reverse(words.begin(), words.end()); // 反转数组
string res; // 答案
for (int i = 0; i < words.size(); i ++ )
{
if (i != words.size() - 1) res += words[i] + ' ';
else res += words[words.size() - 1];
}
return res;
}
};
算法2
class Solution {
public:
string reverseWords(string s) {
reverse(s.begin(), s.end());
s.push_back(' ');
for (int i = 0; i < s.size(); )
{
int l = i, r = i;
while (s[r] != ' ') r ++ ;
i = r + 1;
while (l < r)
{
swap(s[l], s[r]);
l ++ , r -- ;
}
}
return s.substr(1);
}
};