A simple and fast python solution, 46ms

  • 0

    Starting from the first character (from the first string), simply loop through all strings to see if every string contains this character at this index. If it does, examine the next character (pre+1). Otherwise return the longest prefix as soon as we find the first character that doesn't match. Note that the loop will break when pre == shortest (the length of prefix is equal to the length of the shortest string)

    def longestCommonPrefix(self, strs):
        n, pre = len(strs), 0
        if n==0:
            return ""
        shortest = min([len(i) for i in strs])
        while pre < shortest: 
            char = strs[0][pre]
            for i in xrange(1,n):
                if strs[i][pre] != char:
                    return strs[0][:pre]
            pre += 1
        return strs[0][:pre]

Log in to reply

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