问题描述:
第一种方法:对撞指针
#include <iostream>
using namespace std;
/// Two Pointers
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
string reverseString(string s) {
int i = 0, j = s.size() - 1;
while(i < j){
swap(s[i], s[j]);
i ++;
j --;
}
return s;
}
};
int main() {
cout << Solution().reverseString("hello") << endl;
return 0;
}
第二种方法:
class Solution {
public:
string reverseString(string s) {
int start = 0;
int end = s.length() - 1;
char ch = 0;
for (; start < end; start++, end--)
{
ch = s[start];
s[start] = s[end];
s[end] = ch;
}
return s;
}
};