码迷,mamicode.com
首页 > 编程语言 > 详细

344. Reverse String(C++)

时间:2016-05-14 18:44:19      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

344. Reverse String

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

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

 

题目大意:

字符串倒置。

 

解题方法:

第一个字符与最后一个非空字符对换。

 

注意事项:

1.字符串最后一个字符是空字符。

 

C++代码:

1.不良代码:

 1 class Solution {
 2 public:
 3     string reverseString(string s) {
 4     char *f,*e;
 5     char temp;
 6     f=&s[0];
 7     e=&s[s.length()-1];
 8     while(f!=e&f!=&s[s.length()/2])
 9     {
10         temp=*f;
11         *f=*e;
12         *e=temp;
13         f++;
14         e--;
15     }
16     return s;
17     }
18 };

 

2.改进后的代码:

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

 

344. Reverse String(C++)

标签:

原文地址:http://www.cnblogs.com/19q3/p/5492849.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!