字符串数组最长公共前缀

字符串数组最长公共前缀

Longest Common Prefix
  • 给出字符串数组,查找这个数组中所有字符串的最长公共前缀

  • Write a function to find the longest common prefix string amongst an array of strings.

example 1

input: ['asdqowi','asdb', 'asdmnc']
output: 'asd'

思路

  1. i从0开始自增,判断每个字符串 i 位置的字符是否一致,不一致则 i 之前的串为最长公共字符串。

  2. 利用python zip函数的特点:

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9, 10]
zip(a, b, c) is =>
(1, 4, 7)

(2, 5, 8)

(3, 6, 9)
set((1, 1, 1)) = {'1'}
set((1, 1, 2)) = {'1', '2'}

zip(*strs)返回可迭代的zip对象,只要判断set(item)长度大于0,则表明此元素非公共字符。

  1. 下面给出两种算法的代码。

代码

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        prefix = ''
        i = 0
        while True:
            try:
                tmp = strs[0][i]
                for item in strs:
                    if item[i] != tmp:
                        return prefix
            except: #out of index range,表明遍历最短字符串完毕
                return prefix
            prefix += tmp
            i += 1
        return prefix


    def longestCommonPrefix_use_zip(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        prefix = ''
        for _, item in enumerate(zip(*strs)):
            if len(set(item)) > 1:
                return prefix
            else:
                prefix += item[0]
        return prefix

本题以及其它leetcode题目代码github地址: github地址

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值