1. 程式人生 > >LeetCode最長公共字首(Python)

LeetCode最長公共字首(Python)

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

如果不存在公共字首,返回空字串 “”。

示例 1:

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

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

所有輸入只包含小寫字母 a-z 。
class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
if not strs: return '' s1 = min(strs) s2 = max(strs) for i,c in enumerate(s1): if c != s2[i]: return s1[:i] return s1