344. Reverse String

题目描述:

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

Example 1:

Input: "hello"
Output: "olleh"

Example 2:

Input: "A man, a plan, a canal: Panama"
Output: "amanaP :lanac a ,nalp a ,nam A"

解题思路:
考察reverse功能,一头一尾两个下标遍历整个string,使用swap交换元素。

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

 

posted @ 2018-08-11 17:08  gszzsg  阅读(58)  评论(0编辑  收藏  举报