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

算法题来自:https://leetcode-cn.com/problems/longest-common-prefix/description/

猜你喜欢

转载自blog.csdn.net/qiubingcsdn/article/details/81873952