#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
void reverseString(vector<char>& s)
{
if (s.empty())
return;
//双指针递归
reverse(s, s[0],0,s.size()-1);
}
//递归函数
void reverse(vector<char>& s,char ch,int begin,int end)
{
//递归结束条件:begin==end
if (begin >= end)
return;
//否则交换头尾元素
swap(s[begin], s[end]);
reverse(s, ch, begin 1, end-1);
}
};
void test()
{
Solution s;
vector<char> s1 ={ 'H','e','l','l','o' };
s.reverseString(s1);
for (int i = 0; i < s1.size(); i )
cout << s1[i];
}
int main()
{
test();
system("pause");
return 0;
}
双指针无递归写法
代码语言:javascript复制
class Solution {
public:
void reverseString(vector<char>& s)
{
if (s.empty())
return;
int begin = 0;
int end = s.size() - 1;
while (begin < end)
{
swap(s[begin ], s[end--]);
}
}
};