LeetCode-算法编程——14.最长公共前缀

原题目:

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

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

提示:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] 仅由小写英文字母组成

示例 1:

输入:strs = ["flower","flow","flight"]
输出:"fl"

示例 2:

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

分析:

        没想到快速的方法,字符串数组最小为1,假设第一个字符串为公共前缀,依次和后面的去比较,每比较一次,记录下当前的公共前缀,最后就是整字符串数组中最长的公共前缀

代码:

Python3版本

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        #每次比较前临时公共前缀
        temp_str = ""
        #最后结果的最长公共前缀
        common_prefix = strs[0]
        n = len(strs)
        for i in range(1, n):
            #每次索引初始化为0
            common_index, d_index = 0, 0
            des_str = strs[i]
            #满足当前公共前缀和新字符串长度最小的值
            while common_index < len(common_prefix) and d_index < len(des_str):
                #当前字符为相同即公共,否则跳出进行下一次循环
                if common_prefix[common_index] == des_str[d_index]:
                    temp_str = temp_str + common_prefix[common_index]
                else:
                    break
                #索引更新
                common_index = common_index + 1
                d_index = d_index + 1
            #临时公共前缀保存
            common_prefix = temp_str
            #临时公共前缀清空
            temp_str = ""
        return common_prefix

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值