Python with comments

  • 0

    May be a little verbose, but it is faster than most other python solutions (42ms).

    class Solution(object):
        def longestCommonPrefix(self, strs):
            :type strs: List[str]
            :rtype: str
            if not strs: return ""
            # Initial metadata
            prefix_dict = {}
            max_prefix = strs[0]
            max_prefix_len = len(max_prefix)
            # Create lookup table
            for i in range(max_prefix_len + 1):
                prefix_dict[i] = max_prefix[:i]
            for s in strs:
                while max_prefix_len >= 0:
                    max_prefix = s[:max_prefix_len]
                    if prefix_dict[max_prefix_len] == max_prefix: break
                    max_prefix_len -= 1
            return max_prefix

Log in to reply

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