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

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

  • 相关阅读:
    C#:类的成员--属性
    C#:类的成员--字段
    C#:try语句
    solaris11 format zpool
    solaris硬盘格式化分区
    Linux使用pam_tally2.so模块限制登录失败锁定时间
    shell脚本if语句的多种条件参数
    系统重启后,mr程序不生成当前时间段的MRx文件问题
    hadoop学习笔记--找到执行hadoop的入口
    STREAMING HIVE流过滤 官网例子 注意中间用的py脚本
  • 原文地址:https://www.cnblogs.com/yuanzhaoyi/p/6023879.html
Copyright © 2011-2022 走看看