A different Python solution using sorting


  • 1
    M

    The idea is after sorting, only the first and last of the elements need to be compared.

    def longestCommonPrefix(self, strs):
        if len(strs) == 0: return ""
        strs.sort()
        n = 0
        while True:
            try:
                if strs[0][n] == strs[-1][n]:
                    n += 1
                else:
                    return strs[0][:n]
            except:
                return strs[0][:n]

  • 0
    C

    @maxareo cool.


Log in to reply
 

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