Python solution using sorting....very simple!


  • 0
    M
    class Solution(object):
        def longestCommonPrefix(self, strs):
            """
            :type strs: List[str]
            :rtype: str
            """
            if len(strs) == 0:
                return ""
            strs.sort()
            s1 = strs[0]
            s2 = strs[len(strs)-1]
            if s1 and s2 and s1[0] != s2[0]:
                return ""
            i=0
            j=0
            c=0
            while i < len(s1) and j < len(s2):
                if s1[i] == s2[j]:
                    c += 1
                    i += 1
                    j += 1
                else:
                    return s1[:c]
            return s1[:c]
    

Log in to reply
 

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