-1

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"

lulia
  • 3
  • 2
  • 2
    You have a `for` loop with a `break` as its last line. This means it will only iterate once. – 001 Jun 29 '21 at 13:50
  • 1
    Same with the `while` with a `return` as its last line. – 001 Jun 29 '21 at 13:51
  • `if prefix in st:` This will be `True` if `prefix` is anywhere in `st` - not just at the beginning. You can use [startswith()](https://docs.python.org/3/library/stdtypes.html?highlight=startswith#str.startswith) instead. *Edited - fixed typo. – 001 Jun 29 '21 at 14:00

2 Answers2

2

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 ''.

BoarGules
  • 16,440
  • 2
  • 27
  • 44
0

Approach:

  1. First, we will find the shortest string and its length.
  2. Secondly, we will take the first string and match each character with the other strings.
  3. As soon as we encounter a character that does not fit, we will break out of the loop.

Code Solution :


    public String longestCommonPrefix(String[] strs) {
        // Longest common prefix string
        StringBuilder longestCommonPrefix = new StringBuilder();
        // Base condition
        if (strs == null || strs.length == 0) {
            return longestCommonPrefix.toString();
        }
        // Find the minimum length string from the array
        int minimumLength = strs[0].length();
        for (int i = 1; i < strs.length; i++) {
            minimumLength = Math.min(minimumLength, strs[i].length());
        }
        // Loop for the minimum length
        for (int i = 0; i < minimumLength; i++) {
            // Get the current character from first string
            char current = strs[0].charAt(i);
            // Check if this character is found in all other strings or not
            for (String str : strs) {
                if (str.charAt(i) != current) {
                    return longestCommonPrefix.toString();
                }
            }
            longestCommonPrefix.append(current);
        }
        return longestCommonPrefix.toString();
    }
}

Time Complexity : O(m*n)

Space Complexity : O(1)