Leetcode刷题笔记26-最长公共前缀

1. 题目

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

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

说明:

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

2. 示例

示例 1:

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

示例 2:

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

3. 解答

python3 48ms

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if strs == []: return ''
        min_len = 1000
        for e in strs:
            if min_len > len(e):
                min_len = len(e)
        common_pre = ''
        # pos = True
        for i in range(min_len):
            cur = strs[0][i]
            # print(cur)
            for j in range(1, len(strs)):
                if strs[j][i] != cur:
                    # pos = False
                    # break
            # if pos is not True:
                    return common_pre
            else:
                common_pre += cur
        return common_pre

solution = Solution()
strs = ["flower","flow","flight"]
# strs = ["dog","racecar","car"]
common_pre = solution.longestCommonPrefix(strs)
print(common_pre)

猜你喜欢

转载自www.cnblogs.com/Joyce-song94/p/9188729.html
今日推荐