344. Reverse String
Posted come_on
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章