344. Reverse String
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
思路1:
使用一个新的string来存放结果。
1
2
3
4
5
6
7
8
9
10
11
12
|
class Solution {
public :
string reverseString(string s) {
int len = s.size();
string result;
for ( int n = 0; n < len; n++)
{
result.append(1,s.at(len - 1 - n));
}
return result;
}
}; |
思路2:
修改原来string直接得到结果。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
class Solution {
public :
string reverseString(string s) {
int len = s.size();
for ( int i = 0; i < len / 2 ; i++)
{
char a = s[i];
s[i] = s[len - 1 - i];
s[len - 1 - i] = a;
}
return s;
}
}; |
本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1836488