One pass Pythonic solution, ~35 ms


  • 0
    Y
    class Solution(object):
        def longestCommonPrefix(self, strs):
            pref = ""
            if strs:
                pref = strs[0]
            for s in strs:
                if s.startswith(pref):
                    continue
                
                for idx in xrange(len(s)):
                    if pref[idx] != s[idx]:
                        pref = pref[:idx]
                        break
                else:
                    pref = s
            return pref
    

  • 0
    R

    @Yinzo How does the last else work . Can you explain that .


  • 0
    Y

    @rahul8590 else block executes when the for loop finish normally, which means if you break out of it, else block will not execute.


Log in to reply
 

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