Skip to content

Latest commit

 

History

History
76 lines (56 loc) · 1.5 KB

014._longest_common_prefix.md

File metadata and controls

76 lines (56 loc) · 1.5 KB

###14. Longest Common Prefix

题目: https://leetcode.com/problems/longest-common-prefix/

难度:

Easy

思路:

找出最短的string,然后一个一个对比,缺点是时间复杂度会比较高,AC代码,这代码优雅程度也是负数啊


class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if strs == []: return ''
        
        shortStr = ''
        shortLen = float('inf')

        for s in strs:
        	if len(s) < shortLen:
        		shortLen = len(s)
        		shortStr = s

        # print shortStr, shortLen

        n = len(strs)
        i = 0
        same = True
        while i < shortLen and same:
            j = 0
            while j < n :
                if strs[j][i] != shortStr[i]:
                    same = False
                    break
                j += 1
            if same:
                i += 1
            else:
                break
        return shortStr[:i]

看一下别人写的优雅程度 佳

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ""
        longest = strs[0]
        for i in range(len(strs[0])):
            for str in strs:
                if len(str) <= i or strs[0][i] != str[i]:
                    return strs[0][:i]
        return strs[0]

这个题解锁之后可以看到各种各样的解法,to be 读