美文网首页
LeetCode Longest Common Prefix

LeetCode Longest Common Prefix

作者: manyGrasses | 来源:发表于2019-01-31 13:57 被阅读0次

题目

Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".

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.
Note:
All given inputs are in lowercase letters a-z.


解法

对所有字符串的对应位置的元素进行遍历后去重,如果去重后只有一个元素则说明所有字符串再该位置的元素是相同的,继续向后寻找,否则函数返回。

代码示例

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

相关文章

网友评论

      本文标题:LeetCode Longest Common Prefix

      本文链接:https://www.haomeiwen.com/subject/slvksqtx.html