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:

0 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lower-case English letters.

Solution in python:

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""
        if len(strs) == 1:
            return strs[0]
        num_len = len(strs)
        min_len = len(strs[0])
        for item in strs:
            if len(item) < min_len:
                min_len = len(item)
        k = 0
        for j in range(min_len):
            char = strs[0][j]
            for i in range(num_len):
                if strs[i][j] != char:
                    break
            else:
                k += 1
                continue
            break
        return strs[0][:k]
最后修改日期: 2020年10月28日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。