1. 程式人生 > >Python實現“最長公共字首”的兩種方法

Python實現“最長公共字首”的兩種方法

找出字串陣列中最長的公共字元字首

如果,沒有公共字元字首的話就返回空字串""

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

注意:所有輸入字串均為小寫"a-z"

1:先將字串列表按長度從小到大排列,然後以最小的字串為標準進行單個字元比較。時間複雜度:n(o^2)

def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if len(strs)==0:
            return ""
        strs.sort(key=len)
        for i in range(len(strs[0])):
            for j in range(1,len(strs)):
                if strs[0][i] != strs[j][i]:
                    return strs[0][0:i]
        return strs[0]

2:取出字串集合中最小和最大的字串,遍歷小字串和大字串做比較,輸出相應結果。

def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ""
        min_str = min(strs)
        max_str = max(strs)
        for i, j in enumerate(min_str):
            if j != max_str[i]:
                return min_str[:i]
        return min_str