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

LeetCode344:Reverse String

时间:2016-08-21 22:32:04      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

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

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

 

在这里介绍python中字符串翻转的几种方法:

1.步长为-1的切片操作。

1 class Solution(object):
2     def reverseString(self, s):
3         """
4         :type s: str
5         :rtype: str
6         """
7         return s[::-1]

 

 2.交换前后字母位置。

 1 class Solution(object):
 2     def reverseString(self, s):
 3         """
 4         :type s: str
 5         :rtype: str
 6         """
 7         t = list(s)  
 8         l = len(t)  
 9         for i,j in zip(range(l-1, 0, -1), range(l//2)):  
10             t[i], t[j] = t[j], t[i]  
11         return "".join(t)
zip函数可参见文档:http://python.usyiyi.cn/translate/python_278/index.html
zip([iterable, ...])

该函数返回一个以元组为元素的列表,其中第 i 个元组包含每个参数序列的第 i 个元素。返回的列表长度被截断为最短的参数序列的长度。当多个参数都具有相同的长度时,zip()类似于带有一个初始参数为Nonemap()只有一个序列参数时,它返回一个1元组的列表。没有参数时,它返回一个空的列表。

 

3. 递归的方式, 每次输出一个字符。
1 class Solution(object):
2     def reverseString(self, s):
3         """
4         :type s: str
5         :rtype: str
6         """
7         if len(s) <= 1:  
8             return s  
9         return reverseString(s[1:]) + s[0]  

4. 双端队列, 使用extendleft()函数

 1 from collections import deque  
 2 class Solution(object):
 3     def reverseString(self, s):
 4         """
 5         :type s: str
 6         :rtype: str
 7         """
 8         d = deque()  
 9         d.extendleft(s)  
10         return ‘‘.join(d)

 

5.使用for循环, 从左至右输出

1 class Solution(object):
2     def reverseString(self, s):
3         """
4         :type s: str
5         :rtype: str
6         """
7         return ‘‘.join(s[i] for i in range(len(s)-1, -1, -1)) 

以上内容参见博客:http://blog.csdn.net/caroline_wendy/article/details/23438739

 

我在LeetCode上提交的是:

 1 class Solution(object):
 2     def reverseString(self, s):
 3         """
 4         :type s: str
 5         :rtype: str
 6         """
 7         l=len(s)
 8         if l>0:
 9             str=s[l-1]
10             while l!=1:
11                 l-=1
12                 str=str+s[l-1]
13         else:
14             return s
15         return str

 

 

LeetCode344:Reverse String

标签:

原文地址:http://www.cnblogs.com/mzct123/p/5793702.html

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