A concise python solution that does NOT need to use any builtin functions


  • 0
    L

    I noticed that many python solutions used builtin functions to simplify the solution. However, with the exception handling, we do not need to sacrifice any performance to call len() or sorted() or even str.startswith() but still be able to get the solution gracefully.

    class Solution(object):
        def longestCommonPrefix(self, strs):
            """
            :type strs: List[str]
            :rtype: str
            """
            i = 0
            try:
                while True:
                    c = strs[0][i] # IndexError Possible
                    for s in strs[1:]:
                        if s[i] != c: # IndexError Possible
                            raise IndexError # I raised IndexError as well here to make it simple.
                    i += 1
            except IndexError:
                if i > 0:
                    return strs[0][:i]
                else:
                    return ""
    

Log in to reply
 

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