zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    阅读笔记03
    第十三周总结
    阅读笔记02
    第十二周总结
    第十一周总结
    阅读笔记01
    阅读笔记3
    第十一周总结
    阅读笔记
    HDFS-学习总结
  • 原文地址:https://www.cnblogs.com/sxbjdl/p/5811953.html
Copyright © 2011-2022 走看看