My recursive solution for your reference.


  • 0
    L

    compare the first one char for each string , and get the last common str.

    class Solution:
    # @return a string
    def longestCommonPrefix(self, strs):
        if(len(strs)>0 and len(strs[0])>0):
            common=strs[0][0]
            for str in strs:
                if(len(str)==0 or str[0]!=common):
                    return "";
            return common+self.longestCommonPrefix([str[1:] for str in strs]);
        else:
            return "";

Log in to reply
 

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