首页 > 代码库 > 344. Reverse String
344. Reverse String
题目:反转字符串
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
五种解法:
#直接逆序class Solution(object): def reverseString(s): return s[::-1]
耗时56ms
#前后对称位互换class Solution(object): def reverseString(s): li = list(s) l = len(s) for i, j in zip(range(len(l)-1, 0, -1), range(l//2)): li[i], li[j] = li[j], li[i] reurn ‘‘.join(li)
耗时52ms
#递归 逐个逆转class Solution(object): def reverseString(s): if len(s) <=1: return s return self.reverseString(s[1:]) + s[0]
耗时64ms
#使用队列class Solution(object): def reverseString(s): from collections import deque q = deque() q.extendleft(s) return ‘‘.join(q)
耗时60ms
#循环逆序class Solution(object): def reverseString(s): return ‘‘.join([s[i] for i in range(len(s)-1,-1,-1)])
耗时52ms
344. Reverse String
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。