Leetcode14-Longest Common Prefix

2017-09-20  本文已影响0人  LdpcII

14. Longest Common Prefix

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

My Solution

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """

        # str = ''
        # for x in zip(strs[0], strs[1], strs[2]...... ):
        #     if x.count(x[0]) == len(x):
        #         str += x[0]
        #     else:
        #         break
        # return str

        if len(strs) == 0:
            return ""
        str_list, s = [], ''
        try:
            for i in range(len(strs[0])):
                for j in range(len(strs)):
                    str_list.append(strs[j][i])
                if str_list.count(str_list[0]) == len(strs):
                    s += str_list[0]
                    str_list = []
                else:
                    break
            return s
        except:
            return s

Reference (转)

class Solution:
    # @return a string
    def longestCommonPrefix(self, strs):
        if not strs:
            return ""
            
        for i, letter_group in enumerate(zip(*strs)):
            if len(set(letter_group)) > 1:
                return strs[0][:i]
        else:
            return min(strs)

My Solution 2.0

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        str = ''
        for x in zip(*strs):
            if x.count(x[0]) == len(x):
                str += x[0]
            else:
                break
        return str
上一篇 下一篇

猜你喜欢

热点阅读