求最长公共前缀

# 编写一个函数来查找字符串数组中的最长公共前缀。
# 
# 如果不存在公共前缀,返回空字符串 ""。
# 输入: ["flower","flow","flight"]
# 输出: "fl"

方法1:判断每一个元素相同index位置的值是否相同,如果相同,则加入到res列表中。否则直接退出判断。
此方法暴力遍历,实际运行下来内存和效率都还ok。但需要比较多的 if,else,容易出错。

from typing import List

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        res = []
        point = 0
        size = len(strs)
        if size==0:
            return ''
        status = True
        while status:
            for index in range(size):
                if len(strs[index]) > point:
                    if index == 0:
                        res.append(strs[0][point])
                        continue
                    if strs[index][point] != res[-1]:
                        res.pop()
                        status = False
                        break
                else:
                    if index != 0:
                        res.pop()
                    status = False
                    break
            point +=1
        res = ''.join(res)
        return res



方法2:官方推荐的方法,将过程拆分开两步,1是判断并返回两个元素的公共前缀。2是遍历列表,用返回的公共前缀逐项向后比对。

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        size = len(strs)
        if size<1:
            return ''
        prfix = strs[0]
        for i in range(1,size):
            prfix = self.commonPrefix(prfix,strs[i])
        return prfix

    def commonPrefix(self,str1,str2):
        size = min(len(str1),len(str2))
        point = 0
        while point<size and (str1[point] == str2[point]):
            point+=1
        return str1[:point]



if __name__ == '__main__':
    res = Solution().longestCommonPrefix(["aa","a"])
    print(res)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值