• 最长公共前缀


    编写一个函数来查找字符串数组中的最长公共前缀。

    如果不存在公共前缀,返回空字符串 ""。

    示例 1:

    输入: ["flower","flow","flight"]
    输出: "fl"
    示例 2:

    输入: ["dog","racecar","car"]
    输出: ""
    解释: 输入不存在公共前缀。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/longest-common-prefix

    方法一:利用python的max()和min(),按照ascII值排,利用字母顺序比较。举例abb, aba,abac,最大为abb,最小为aba。比较出来最大最小的公共前缀就是整个数组的公共前缀

        def longestCommonPrefix(self, strs):
            if not strs: return ""
            s1 = min(strs)
            s2 = max(strs)
            for i,x in enumerate(s1):
                if x != s2[i]:
                    return s2[:i]
            return s1

         1.    判断是否为None的情况

        if not x

        if x is None

        if not x is None

     

        if x is not None`是最好的写法,清晰,不会出现错误,以后坚持使用这种写法。

        使用if not x这种写法的前提是:必须清楚x等于None,  False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行

        链接:https://www.cnblogs.com/chenya/p/4218761.html

          2.   enumerate() 函数

        用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

     语法:

        enumerate(sequence,[start=0])

     实例:

    >>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
    >>> list(enumerate(seasons))
    [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
    >>> list(enumerate(seasons, start=1))       # 下标从 1 开始
    [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

     方法二:利用python的zip函数,把str看成list然后把输入看成二维数组,左对齐纵向压缩,然后把每项利用集合去重,之后遍历list中找到元素长度大于1之前的就是公共前缀

        def longestCommonPrefix(self, strs):
            if not strs: return ""
            ss = list(map(set, zip(*strs)))
            res = ""
            for i, x in enumerate(ss):
                x = list(x)
                if len(x) > 1:
                    break
                res = res + x[0]
            return res

    1.zip()内置函数

    链接:https://www.runoob.com/python/python-func-zip.html

  • 相关阅读:
    rand()和srand()
    advanced regression to predict housing prices
    数学建模
    python的对数
    八月总结——人工智能初学者
    看到的不错的项目
    学习笔记(七): Logistic Regression
    学习笔记(六): Regularization for Simplicity
    An Intuitive Explanation of Convolutional Neural Networks
    CentOS7的mysql5.7-rpm.bundle方式安装
  • 原文地址:https://www.cnblogs.com/biu-biu-biu-/p/11564788.html
Copyright © 2020-2023  润新知