LeetCode 14. 最长公共前缀 (Python)

问题:

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

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

示例 1:

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

示例 2:

输入: ["dog","racecar","car"]
输出: ""

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


Solution:

  • 思路:取每一个单词的同一位置的字母,看是否相同
class Solution(object):
    def longestCommonPrefix(self, strs):
        # type strs: List[str]
        res = ''
        for tmp in zip(*strs):
            tmp_set = set(tmp)
            if len(tmp_set) == 1:
                res += tmp[0]
            else:
                break
        return res
  • zip()可以看作是压缩,zip(*)可以看作是解压

  • zip()和zip(*)的用法与区别可以参照这篇文章

  • set() 函数创建一个无序不重复元素集

本题来自:https://leetcode-cn.com/problems/longest-common-prefix/

你可能感兴趣的:(Leetcode,Python)