LeetCode344:Reverse String@Python
2016-08-21 21:46
357 查看
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
在这里介绍python中字符串翻转的几种方法:
1.步长为-1的切片操作。
2.交换前后字母位置。
zip函数可参见文档:http://python.usyiyi.cn/translate/python_278/index.htmlzip([iterable, ...])
该函数返回一个以元组为元素的列表,其中第 i 个元组包含每个参数序列的第 i 个元素。返回的列表长度被截断为最短的参数序列的长度。当多个参数都具有相同的长度时,zip()类似于带有一个初始参数为None的map()。只有一个序列参数时,它返回一个1元组的列表。没有参数时,它返回一个空的列表。
3. 递归的方式, 每次输出一个字符。
4. 双端队列, 使用extendleft()函数。
5.使用for循环, 从左至右输出。
以上内容参见博客:http://blog.csdn.net/caroline_wendy/article/details/23438739
我在LeetCode上提交的是:
Example:
Given s = "hello", return "olleh".
在这里介绍python中字符串翻转的几种方法:
1.步长为-1的切片操作。
class Solution(object): def reverseString(self, s): """ :type s: str :rtype: str """ return s[::-1]
2.交换前后字母位置。
class Solution(object): def reverseString(self, s): """ :type s: str :rtype: str """ t = list(s) l = len(t) for i,j in zip(range(l-1, 0, -1), range(l//2)): t[i], t[j] = t[j], t[i] return "".join(t)
zip函数可参见文档:http://python.usyiyi.cn/translate/python_278/index.htmlzip([iterable, ...])
该函数返回一个以元组为元素的列表,其中第 i 个元组包含每个参数序列的第 i 个元素。返回的列表长度被截断为最短的参数序列的长度。当多个参数都具有相同的长度时,zip()类似于带有一个初始参数为None的map()。只有一个序列参数时,它返回一个1元组的列表。没有参数时,它返回一个空的列表。
3. 递归的方式, 每次输出一个字符。
class Solution(object): def reverseString(self, s): """ :type s: str :rtype: str """ if len(s) <= 1: return s return reverseString(s[1:]) + s[0]
4. 双端队列, 使用extendleft()函数。
from collections import deque class Solution(object): def reverseString(self, s): """ :type s: str :rtype: str """ d = deque() d.extendleft(s) return ''.join(d)
5.使用for循环, 从左至右输出。
class Solution(object): def reverseString(self, s): """ :type s: str :rtype: str """ return ''.join(s[i] for i in range(len(s)-1, -1, -1))
以上内容参见博客:http://blog.csdn.net/caroline_wendy/article/details/23438739
我在LeetCode上提交的是:
class Solution(object): def reverseString(self, s): """ :type s: str :rtype: str """ l=len(s) if l>0: str=s[l-1] while l!=1: l-=1 str=str+s[l-1] else: return s return str
相关文章推荐
- 【python】【leetcode】【算法题目344—Reverse String】
- Python [Leetcode 344]Reverse String
- python--leetcode344. Reverse String
- leetcode No344.Reverse String Note
- LeetCode-344.Reverse String
- LeetCode *** 344. Reverse String
- LeetCode344—Reverse String
- Leetcode:344. Reverse String
- LeetCode 344. Reverse String
- LeetCode 第 344 题(Reverse String)
- LeetCode笔记:344. Reverse String
- leetcode_344 Reverse String
- leetcode——344——Reverse String
- leetcode 344. Reverse String 题解
- [leetcode 344]Reverse String
- Leetcode 344 Reverse String 字符串处理
- Leetcode Reverse String 344
- LeetCode 344. Reverse String
- <LeetCode>344. Reverse String
- 344. Reverse String [easy] (Python)