5/09/2020

[LeetCode] 14. Longest Common Prefix

Problem : https://leetcode.com/problems/longest-common-prefix/

Iterate all strings to find the common prefix.

Time Complexity :  O ( min ( length of all strings ) )
Space Complexity:  O ( len( common-prefix ) )

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        
        result = ""
        
        # handle edge condition for empty string array
        if not strs:
            return result
        
        # caculate the minimum length of strings
        L = min([len(s) for s in strs])
    
        for i in range(L):
            tmp = strs[0][i]
            for s in strs:
                if s[i] != tmp:
                    # break the loop when reach to the first non-common character
                    return result
            else:
                result += tmp
            
        return result

No comments:

Post a Comment