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

  • 相关阅读:
    css引入讲解及media
    css中的media
    IE6存在的一些兼容
    Eclipse 反编译插件JadClipse安装
    JavaScript 常用功能总结
    241个jquery插件—jquery插件大全
    javascript深入理解js闭包
    JS拖拽插件实现步骤
    JavaScript拖拽原理的实现
    js实现拖拽效果
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14671910.html
Copyright © 2011-2022 走看看