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

  • 相关阅读:
    结构体的malloc与数组空间
    绘制K线图
    加载文件
    数据分析(绘图)
    GIT操作
    疑难杂症汇总
    Shell编程2
    shell编程1
    shell命令2
    Shell命令1
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14671910.html
Copyright © 2011-2022 走看看