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

    题目:

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

    Subscribe to see which companies asked this question

    代码:

    上周出差北京一周,都没有做题,这两天继续开始,先从简单的入手。

    这个题目一开始以为是找出字符串数组中最长的那个,那不很简单嘛,很快写完了,发现不对。

    题目表达不是很清楚,或者是我英语不行,查了下,原来是找出字符串数组中最长的共有前缀。

    于是乎,开始凑答案啦!继续用python,写起来比较简单:)

    class Solution(object):
        def longestCommonPrefix(self, strs):
            """
            :type strs: List[str]
            :rtype: str
            """
            result = ""
            #输入[],返回""
            if len(strs) == 0:
                return result
            #flag用来判断字符串前缀是否存在于所有的字符串中
            flag=True
            #以数组中第一个字符串为例,逐步取它的前一位、两位、三位...作为前缀,去数组中所有字符串中判断
            #直至失败,说明该字符串不符合要求,于是退回一位到符合要求的字符串前缀,返回结果
            j=1
            while j in range(1,len(strs[0])+1) and flag:
                result=strs[0][0:j]
                
                for i in strs:
                    if result not in i[0:j]:
                        flag = False
                        result=result[:-1]
                        break
                j += 1
            return result

    发现结果居然效率还不错:

  • 相关阅读:
    hdu4280 Island Transport(最大流Dinic数组模拟邻接连边)
    hihoCoder1378 (最大流最小割)
    单聊语音
    Mybatis批量更新数据
    mysql 之 MRR
    Intellij IDEA 快捷键整理
    SpringBoot 整合 Swagger2 使用教程
    jdk/dubbo spi
    redis问题(待解决)
    JVM调优心得
  • 原文地址:https://www.cnblogs.com/yuanzhaoyi/p/6023879.html
Copyright © 2011-2022 走看看