zoukankan      html  css  js  c++  java
  • Leetcode 14. Longest Common Prefix

    Description: Write a function to find the longest common prefix string amongst an array of strings.

    If there is no common prefix, return an empty string ""

    Link: 14. Longest Common Prefix

    Examples:

    Example 1:
    Input: strs = ["flower","flow","flight"]
    Output: "fl"
    
    Example 2:
    Input: strs = ["dog","racecar","car"]
    Output: ""
    Explanation: There is no common prefix among the input strings.

    思路:计算得到最短的string的长度,然后在这个长度内遍历每个字母是否common for all strings.

    class Solution(object):
        def longestCommonPrefix(self, strs):
            """
            :type strs: List[str]
            :rtype: str
            """
            if not strs: return ''
            min_len = min([len(s) for s in strs])
            res = ''
            for i in range(min_len):
                if len(set([s[i] for s in strs])) == 1:
                    res += strs[0][i]
                else:
                    break
            return res

    我们也可以不去计算最短的string长度,而是直接任意选一个string,然后用try, except IndexError 来处理。

    class Solution(object):
        def longestCommonPrefix(self, strs):
            """
            :type strs: List[str]
            :rtype: str
            """
            if not strs: return ''
            res = ''
            for i in range(len(strs[0])):
                try: 
                    if len(set([s[i] for s in strs])) == 1:
                        res += strs[0][i]
                    else:
                        return res
                except IndexError:
                    return res
            return res

    日期: 2021-04-17

  • 相关阅读:
    wifi 与 以太网 以及 修改网络查看网络
    git 与 gitHub 与 gitLab ,git常用5个命令
    花生壳
    诗词古文
    基金龙虎榜
    osm_mano安装
    db2快速删除大表数据(亲测可用)
    行列转换
    DB2表空间
    表分区,和分表区别
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14671910.html
Copyright © 2011-2022 走看看