14. Longest common prefix

https://leetcode.com/problems/longest-common-prefix/description/

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 1: Input: strs = [“flower”,“flow”,“flight”] Output: “fl” Example 2: Input: strs = [“dog”,“racecar”,“car”] Output: "" Explanation: There is no common prefix among the input strings.

Constraints:

1 <= strs.length <= 200 	
0 <= strs[i].length <= 200 	
strs[i] consists of only lowercase English letters

  • code
class Solution {
    public String longestCommonPrefix(String[] strs) {
        int prefixLen = strs[0].length();
        String res = strs[0];
        for (String s: strs){
            prefixLen = Math.min(prefixLen, s.length());
            while (!s.substring(0, prefixLen).equals(res.substring(0, prefixLen))){
                prefixLen--;
                if (prefixLen == 0) return "";
            }
        }
        return res.substring(0, prefixLen);
    }
}
  • code
def longestCommonPrefix(self, strs: List[str]) -> str:
        if strs == []:
            return ""
        common = strs[0]
        index = len(common)
        for i in strs[1:]:
            index = min(index, len(i))
            while (common[:index] != i[:index]):
                index -= 1
        return "" if index == -1 else common[:index]
  • code
class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        l = list(zip(*strs))
        prefix = ""
        for i in l:
            if len(set(i))==1:
                prefix += i[0]
            else:
                break
        return prefix

l = list(zip(*strs))

l = [(‘f’, ‘f’, ‘f’), (‘l’, ‘l’, ‘l’), (‘o’, ‘o’, ‘i’), (‘w’, ‘w’, ‘g’)]