Skip to content

Latest commit

 

History

History
61 lines (46 loc) · 1.51 KB

14.md

File metadata and controls

61 lines (46 loc) · 1.51 KB

Longest Common Prefix

Description

link


Solution

see Code

排序之后只需要比较最长和最短的二者,因为在排序过程中总是先通过第一个字符的顺序,然后是第二个字符的顺序,所以如果第一个和最后一个相同,那么中间的每一个都相同

当然也可以用我自己写的方法,直接比较,不需要排序,比较的轮数会多,但是舍去了排序的时间,总体来说时间复杂度并没有增加多少


Code

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if len(strs) == 0:
            return ""
        if len(strs) == 1:
            return strs[0]
        
        strs = sorted(strs)
        
        s1 = strs[0]
        s2 = strs[-1]
        
        prefix = ""
        for index in range(min(len(s1), len(s2))):
            if s1[index] == s2[index]:
                prefix += s1[index]
            else:
                break
        
        return prefix

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        prefix = ""
        if strs:
            for i in range(len(strs[0])):
                if all([len(s) > i for s in strs]) and all([s[i] == strs[0][i] for s in strs]):
                    prefix += strs[0][i]
                else:
                    break
        return prefix