14.leetcode 最长公共前缀(简单)

leetcode python 刷题记录,从易到难

一、题目

在这里插入图片描述

二、解答

1.思路

遍历第一个字符串的每个字母,比较第一个字符串的每个字母的索引和其他字符串的长度,如果索引(index)等于长度,则返回前缀strs[0](0,index],如果长度大于索引则继续。比较第一个字符串的每个字母和其他字符串对应索引处的字母是否相同,如果不同则返回前缀strs[0](0,index],相同则继续往下比较。如果循环结束,仍旧没找到满足上面条件的,说明第一个字符串就是最大前缀,返回第一个字符串即可。

2.实现

class Solution:
    def longestCommonPrefix(self, strs):
        if not strs:
            return ""
        length = len(strs[0])
        count = len(strs)
        for i in range(length):
            point = strs[0][i]
            for j in range(1, count):
                if i == len(strs[j]) or strs[j][i] != point:
                    return strs[0][:i]
        return strs[0]

3.提交结果

在这里插入图片描述

Github地址

https://github.com/m769963249/leetcode_python_solution/blob/master/easy/14.py

参考链接

https://leetcode-cn.com/

猜你喜欢

转载自blog.csdn.net/qq_39945938/article/details/107325248