首页 > 编程语言 > 详细

344. Reverse String(C++)

时间:2016-05-14 18:43:33      阅读:254      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!