1、题目描述
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
2、C++实现
class Solution {
public:
string reverseString(string s) {
string s_reverse(s); //①
int length=s.size(); //②
for(int i=length-1;i>=0;--i){
s_reverse[length-1-i]=s[i];
}
return s_reverse;
}
};
3、经验教训
①不能直接string s_reverse,一定要s_reverse(s),否则不能用s_reverse的索引。
②s.length()等同s.size(),这是早期开发string类时加入的,现在还可以用,但其他STL容器没有此方法。