PU Longest Common Prefix

Jan 01, 1970

Write a function to find the longest common prefix string amongst an array of strings.

Python Solution 1:

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs: return ""
        res = []
        while True:
            for s in strs:
                if len(res) >= len(s):
                    return "".join(res)
                if s[len(res)] == strs[0][len(res)]: continue
                return "".join(res)
            res.append(strs[0][len(res)])

Python Solution 2:

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs: return ""
        for i, val in enumerate(zip(*strs)):
            if len(set(val)) > 1:
                return strs[0][:i]
        return min(strs)

Summary:

  • Pythonic

LeetCode: 14. Longest Common Prefix