首页 > 其他 > 详细

LeetCode: 344 Reverse String

时间:2017-08-23 12:34:25      阅读:141      评论:0      收藏:0      [点我收藏+]

题目:

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

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

 代码:

 自己的:

 1 class Solution {
 2 public:
 3     string reverseString(string s) {
 4         stack<char> tem;
 5         string result;
 6         for ( auto c : s)
 7             tem.push(c);
 8         while (!tem.empty()){
 9             result += tem.top();
10             tem.pop();
11         }
12         return result;
13     }
14 };

别人的:

 1 class Solution {
 2 public:
 3     string reverseString(string s) {
 4         if (s.size() < 2)
 5             return s;
 6         int l = 0, r = static_cast<int>(s.size() - 1);
 7         while (l < r)
 8         {
 9                 swap(s[l++], s[r--]);
10         }
11         return s;
12     }
13 };

别人的效率好。

swap()函数:交换

 

LeetCode: 344 Reverse String

原文:http://www.cnblogs.com/llxblogs/p/7417308.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!