LeetCode #14 – Longest Common Prefix

链接:https://leetcode.com/problems/longest-common-prefix/

题目:Write a function to find the longest common prefix string amongst an array of strings.

题意:给定一些字符串,找出最常公共前缀

分析:直接暴力做就可以,最常前缀的长度不长于最短的字符串。

代码:

class Solution:
    def longestCommonPrefix(self, strs):
        if(len(strs)==0): return ''
        s = min([len(i) for i in strs])
        for i in range(s):
            cur = strs[0][i]
            for j in range(1, len(strs)):
                if cur != strs[j][i]:
                    return strs[0][0:i]
        return strs[0][0:s]

欢迎留言