zoukankan      html  css  js  c++  java
  • 将字符串翻转

    举例:翻转字符串“algorithm”

    准备两个指针,一个从前到中间遍历,一个从后向中间遍历,交换两个指针所指的字符。

    注意:由于无法直接修改字符串里的字符,所以必须先把字符串变换为数组,然后再运用这个算法。

    class Solution:
        def reverseString(self, s):
            """
            :type s: str
            :rtype: str
            """
            s = list(s)
            i, j = 0, len(s) - 1
            while i < j:
                s[i], s[j] = s[j], s[i]
                i += 1
                j -= 1
            return "".join(s)
    
    
    a = "abdfdf"
    solution = Solution()
    print(solution.reverseString(a))  # fdfdba

    数组的优缺点

     优点:

    • 构建非常简单

    • 能在 O(1) 的时间里根据数组的下标(index)查询某个元素

     缺点:

    • 构建时必须分配一段连续的空间
    • 查询某个元素是否存在时需要遍历整个数组,耗费 O(n) 的时间(其中,n 是元素的个数)
    • 删除和添加某个元素时,同样需要耗费 O(n) 的时间
  • 相关阅读:
    Pascal's Triangle II
    Pascal's Triangle
    Path Sum II
    Path Sum
    plusOne
    Divide Two Integers
    64. ZigZag Conversion
    63. Swap Nodes in Pairs && Rotate List && Remove Nth Node From End of List
    62. Divide Two Integers
    61. Unique Paths && Unique Paths II
  • 原文地址:https://www.cnblogs.com/zhaoyingjie/p/13996648.html
Copyright © 2011-2022 走看看