Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
解法1(不好):
class Solution {
public:
string reverseString(string s)
{
string a;
const char *t = s.c_str();//string转char*
int length=s.length();
char p[length];//注意数组长度
// if(length<2) //考虑边界条件
// return s;
for(int i=0;i<length;i++)
{
p[i]=t[length-i-1];
}
p[length]=t[length];//不加有些过不去
a=p;//char*可以直接转换成string
std::cout<<length<<std::endl;
return a;
}
};
参考解:
class Solution {
public:
string reverseString(string s)
{
int start = 0;
int end = s.length() - 1;//或者 s.size(),不能用sizeof(s)
char ch = 0;
for (; start < end; start++, end--)
{
ch = s[start];//string类型可以用下标访问
s[start] = s[end];
s[end] = ch;
}
return s;
}
};