1. 程式人生 > >Leetcode篇:最長公共前綴

Leetcode篇:最長公共前綴

每一個 return 函數 soft file str 字符串數組 不重復 car


@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)

Leetcode篇:最長公共前綴