Leetcode 14:最长公共前缀(超详细的解法!!!)

版权声明:本文为博主原创文章,未经博主允许不得转载。有事联系:[email protected] https://blog.csdn.net/qq_17550379/article/details/84746801

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

示例 1:

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

示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。

说明:

所有输入只包含小写字母 a-z

解题思路

首先想到的最简单的处理思路就是先从这么多的字符串中挑选出最短的那个min_str,然后我们遍历这个min_str的所有字符,判断是不是其他字符串中的前缀中都包含它即可。

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ''
        res = ''
        min_len, min_index = len(strs[0]), 0
        for i, s in enumerate(strs[1:]):
            if len(s) < min_len:
                min_len = len(s)
                min_index = i + 1
                
        strs[0], strs[min_index] = strs[min_index], strs[0]
        for i, c in enumerate(strs[0]):
            if not all([s[i] == c for s in strs[1:]]):
                break
            res += c
                
        return res
        

因为这是一个前缀问题,所以我们使用zip这个内建函数可以很快解决这个问题(将一个行问题变成一个列问题)。

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ''
        for i, word in enumerate(zip(*strs)):
            if len(set(word)) > 1:
                return strs[0][:i]
        else:
            return min(strs)            

我将该问题的其他语言版本添加到了我的GitHub Leetcode

如有问题,希望大家指出!!!

猜你喜欢

转载自blog.csdn.net/qq_17550379/article/details/84746801
今日推荐