python implementation easy to understand (beats 80%)


  • 0
    X
    class Solution(object):
        def longestCommonPrefix(self, strs):
            """
            :type strs: List[str]
            :rtype: str
            """
            l1 = len(strs)
            if l1>1:
                s = []
                s1 = []
                for i in range(l1):
                    l2 = len(strs[i])
                    s.append(l2)
                l2 = min(s)
                d = 0
                for j in range(l2):
                    c = 0
                    for k in range(l1-1):
                        if strs[k][j] == strs[k+1][j]:
                            c += 1
                        else:
                            d = 1
                    if c == (l1-1) and d == 0:
                        s1.append(strs[k][j])
                if s1:
                    return ''.join(s1)
                else:
                    return ''
            elif l1 == 1:
                return strs[0]
            else:
                return ''
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.