码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: 344 Reverse String

时间:2017-08-23 13:46:31      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:题目   int   for   stack   function   效率   ati   函数   des   

题目:

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

标签:题目   int   for   stack   function   效率   ati   函数   des   

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

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