Straightforward Python solution using 45ms


  • 0
    def longestCommonPrefix(self, string_list):
            if not string_list:
                return ""
                
            def unify_length(string_list):
            	mini = float("inf")
            	for string in string_list:
            		if len(string) < mini:
            			mini = len(string)
            
            	for i in xrange(len(string_list)):
            		upper = mini - len(string_list[i]) if len(string_list[i]) > mini else len(string_list[i])
            		string_list[i] = string_list[i][:upper]
    
            def shorten(string_list):
            	for i in xrange(len(string_list)):
            		string_list[i] = string_list[i][:-1]   
            		
        	unify_length(string_list)
        	while len(set(string_list)) != 1:
        		shorten(string_list)
        	return string_list[0]
    

Log in to reply
 

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