1. 程式人生 > >python入門習題——14,最長公共字首(簡單)

python入門習題——14,最長公共字首(簡單)

編寫一個函式來查詢字串陣列中的最長公共字首。

如果不存在公共字首,返回空字串 ""

示例 1:

輸入: ["flower","flow","flight"]
輸出: "fl"

示例 2:

輸入: ["dog","racecar","car"]
輸出: ""
解釋: 輸入不存在公共字首。

說明:

所有輸入只包含小寫字母 a-z 。


class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        res = ""
        if len(strs) == 0:
            return ""
        for item in zip(*strs):
            if len(set(item)) == 1:
                res += item[0]
            else:
                return res
        return res