Longest Common Prefix

LeetCode 14

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        # zip (*str) unpack strs then zip
        # return an iterator of tuples 
        # where the i-th tuple contains the i-th element from each of the argument sequences
        # ['a1b1c1', 'a2b2c2', 'a3b3c3'] -> [(a1,a2,a3), (b1,b2,b3), (c1,c2,c3)]
        strr = zip(*strs) 
        res = ""
        
        for c in strr:
            if len(set(c)) > 1:
                break
            else:
                res += c[0]
        return res
        

Last updated