子串判断

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zslngu/article/details/89116206
KMP 算法

题目描述
现有一个小写英文字母组成的字符串s和一个包含较短小写英文字符串的数组p,请设计一个高效算法,对于p中的每一个较短字符串,判断其是否为s的子串。

给定一个string数组p和它的大小n,同时给定string s,为母串,请返回一个bool数组,每个元素代表p中的对应字符串是否为s的子串。保证p中的串长度小于等于8,且p中的串的个数小于等于500,同时保证s的长度小于等于1000。

测试样例:
["a","b","c","d"],4,"abc"
返回:[true,true,true,false]

KMP

# -*- coding:utf-8 -*-

class Substr:
    
    def getNext(self, s):
        nexts = [-1 for ss in s]
        j = 0
        k = -1
        while j<len(s)-1:
            if k == -1 or s[j] == s[k]:
                nexts[j+1] = k+1
                j += 1
                k += 1
            else:
                k = nexts[k]
        return nexts
    
    def find(self, source, desc, nexts):
        sL = len(source)
        dL = len(desc)
        i = 0
        j=0
        while i<sL and j<dL:
            if j==-1 or source[i] == desc[j]:
                i += 1
                j += 1
            else:
                j = nexts[j]
        if j==dL:
            return i-j
        return -1
                
    
    def chkSubStr(self, p, n, s):
        # write code here
        maps = {}
        result = []
        for pp in p:
            maps[pp] = self.getNext(pp)
            if self.find(s,pp,  maps[pp]) != -1:
                result.append(True)
            else:
                result.append(False)
        return result

猜你喜欢

转载自blog.csdn.net/zslngu/article/details/89116206