• Leetcode题库——14.最长公共前缀



    @author: ZZQ
    @software: PyCharm
    @file: longestCommonPrefix.py
    @time: 2018/9/16 17:50
    要求:查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""
    e.g.: 输入: ["flower","flow","flight"] 输出: "fl"
    输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。

    class Solution():
        def __init__(self):
            pass
    
        def longestCommonPrefix(self, strs):
            """
            :type strs: List[str]
            :rtype: str
            """
    
            list_len = len(strs)
            if list_len > 1:
                str_len = min(len(f) for f in strs)
                longest_substr = ""
                for j in range(0, str_len):
                    c = strs[0][j]
                    index = 0
                    for i in range(1, list_len):
                        if c == strs[i][j]:
                            index += 1
                            print strs[i][j]
                    if index == (list_len-1):
                        longest_substr += c
                    else:
                        return longest_substr
                return longest_substr
            else:
                if list_len == 1:
                    return strs[0]
                else:
                    return ""
    
        def longestCommonPrefix2(self, strs):
            res = ""
            if len(strs) == 0:
                return ""
            # zip()函数用于将可迭代对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表
            for each in zip(*strs):
                # print each  # each 是由strs字符串列表中每一个对象的对应位置的元素组成的元祖。
                # 利用集合创建一个无序不重复元素集
                print(set(each))
                if len(set(each)) == 1:
                    res += each[0]
                else:
                    return res
            return res
    
    
    if __name__ == "__main__":
        strs = ["dog", "racecar", "car"]
        strs = ["flower", "flow", "flight"]
        # strs = ["dog"]
        # strs = ["aca", "cba"]
        answer = Solution()
        print answer.longestCommonPrefix2(strs)
    
    CV小蜡肉
  • 相关阅读:
    ListView的Item被点击和其中的Button被点击同时生效
    Android Canvas绘图详解(图文)
    Android--获取当前系统的语言环境
    自定义seekbar中,thumb被覆盖掉一部分问题
    Android类参考---Fragment
    使用LocalBroadcastManager
    寒哥细谈之AutoLayout全解
    Xcode6中自动布局autolayout和sizeclass的使用
    Swift 2.0初探:值得注意的新特性
    swift调用相机和相册
  • 原文地址:https://www.cnblogs.com/zzq-123456/p/9671332.html
Copyright © 2020-2023  润新知