pythonstringwhile-looplongest-prefix

Longest Common Prefix


Write a function to find the longest common prefix string amongst an array of strings If there is no common prefix, return an empty string "". Example: Input: strs = ["flower","flow","flight"] Output: "fl" I'm new in coding and try to solve this problem (from leetcode). my way is search the shortest string between strings, here is my code, I can't figure out where did I do wrong, it seems the while loop doesn't work at all. I appreciate if someone could help me. here is my code:

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        string = ""
        len_st = []
        for st in strs:
            len_st.append(len(st))
        m = min(len_st)
        prefix = strs[len_st.index(m)]
        while prefix:
            for st in strs:
                if prefix in st:
                    continue
                else:
                    prefix = prefix.replace(prefix[-1], "")
                break
            return prefix
        else:
            return ""

input : ["flower","flow","flight"] output: "flo" expected output: "fl"


Solution

  • There really is no need to loop through it manually at all. Let Python do that for you.

    def longestCommonPrefix(self, strs: List[str]) -> str:
        assert len(strs) > 0
        prefix = min(strs,key=len)
        while not all(s.startswith(prefix) for s in strs):
            prefix = prefix[:-1]
        return prefix
    

    This uses min() to return the shortest word (or one if them) and chooses that as the candidate prefix. Then it checks to see if all the offered words begin with the prefix. Calling all() will terminate the checking at the first failure. Then it tries again with a shorter candidate prefix, until all of the words start with that, or the prefix is ''.