LeetCode 14. 最长公共前缀 Longest Common Prefix

135 阅读2分钟

Table of Contents

一、中文版

二、英文版

三、My answer

四、解题报告

 


一、中文版

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""。

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"
示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
说明:

所有输入只包含小写字母 a-z 。

来源:力扣(LeetCode)
链接:leetcode-cn.com/problems/lo…
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、英文版

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: ["flower","flow","flight"]
Output: "fl"
Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:

All given inputs are in lowercase letters a-z.

 

三、My answer

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""
        if len(strs) == 1:
            return strs[0]
        
        min_len = len(strs[0])
        for item in strs:
            if len(item) < min_len:
                min_len = len(item)
        i, j = 0 ,1        
        for i in range(min_len):
            for j in range(1,len(strs)):
                if strs[j][i] != strs[j-1][i]:
                    return strs[0][0:i]
                
        if i == min_len-1 and j == len(strs)-1:
            return strs[0][:min_len]
        return ""

四、解题报告

数据结构:数组,字符串

算法:遍历

实现:纵向遍历。看 strs 数组中每一个字符串的第 i 位是否相同,如果相同则继续,不同则返回结果。

注意:特判 i 和 j 都遍历到最后一位时的情况,如果不加特判,那么如 ["aa","a"] 就会出错。