几种办法:
1)交换字符法
class Solution {
public:
string reverseString(string s) {
int i = 0;
int len = s.size();
string res = s;
while (i <= (len-1) / 2){
char temp = res[i];
res[i] = res[len-i-1];
res[len-i-1]= temp;
i += 1;
}
return res;
}
};
2)栈的方法
class Solution {
public:
string reverseString(string s) {
stack<char>temp;
for (int i = 0; i<s.size();++i){
temp.push(s[i]);
}
string res;
while(!temp.empty()){
char t;
t = temp.top();
res = res + t;
temp.pop();
}
return res;
}
};
报了Memory Limit Exceeded
的错误
把res = res + t 改成了res.push_back(t)