鱼C论坛

 找回密码
 立即注册
查看: 1659|回复: 2

求助大佬关于python最长前缀的问题

[复制链接]
发表于 2021-10-24 18:35:30 | 显示全部楼层 |阅读模式
20鱼币
1.代码运行后为空
2.代码的意思不是很懂:
     1.stillmatch的作用是什么?还有True和Flase
     2.最后return strs[0][:start -1],为什么要减1呢?

class Solution:
    def longestCommonPrefix(self, strs: list[str]) -> str:
        start = 1
        stillmatch = True
        while start <= len(strs[0]):

            #将字符串数组第一个字符串之后的字符串分别与第一个字符比较
            for j in range(1, len(strs)):
                if strs[0][:start] != strs[j][:start]:
                    stillmatch = False
                    break

            #一旦发现不匹配则可以退出循环
            if not stillmatch:
                break

            #更新比较的字符串前缀的位置
            start += 1

        return strs[0][:start-1]


其他方法麻烦大佬写个注释,谢谢!!

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2021-10-24 18:36:08 | 显示全部楼层
最好是其他办法
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2021-10-24 22:03:27 | 显示全部楼层
这个代码运行也是为空
class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ""
        
        strs.sort()
        res = ""
        
        for x, y in zip(strs[0], strs[-1]):
            if x == y:
                res += x
            else:
                break
        
        return res
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-12 11:36

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表