Leetcode 344. Reverse String

Write a function that takes a string as input and returns the string reversed.

Example: Given s = "hello", return "olleh".

解法一:直接用reverse函数

1 class Solution {
2 public:
3     string reverseString(string s) {
4         reverse(s.begin(), s.end());
5         return s;
6         
7     }
8 };
View Code

解法二:利用两个指针,首尾元素互换

 1 class Solution {
 2 public:
 3     string reverseString(string s) {
 4         int len = s.length();
 5         for(int i = 0, j = len - 1; i < j; i++, j--){
 6             swap(s[i], s[j]);
 7         }
 8         return s;
 9         
10     }
11 };
View Code

 

posted @ 2016-05-19 20:50  琴影  阅读(161)  评论(0编辑  收藏  举报