其他题目---KMP算法

来源:互联网 发布:java静态变量 定义 编辑:程序博客网 时间:2024/06/09 21:49

【题目】

  给定两个字符串str和match,长度分别为N和M。实现一个算法,如果字符串str中含有子串match,则返回match在str中的开始位置,不含有则返回-1。

【代码实现】

#python3.5def getIndexOf(strS, strM):    def getNextArray(str1):        if len(str1) == 1:            return [-1]        nextArr = [0 for i in range(len(str1))]        nextArr[0] = -1        nextArr[1] = 0        pos = 2        cn = 0        while pos < len(str1):            if str1[pos-1] == str1[cn]:                nextArr[pos] = cn + 1                pos += 1                cn += 1            elif cn == 0:                nextArr[pos] = 0                pos += 1            else:                cn = nextArr[cn]        return nextArr    if strS == None or strM == None or len(strM) < 1 or len(strS) < len(strM):        return -1    nextArr = getNextArray(strM)    si = 0    mi = 0    while si < len(strS) and mi < len(strM):        if strS[si] == strM[mi]:            si += 1            mi += 1        elif mi == 0:            si += 1        else:            mi = nextArr[mi]    return -1 if mi != len(strM) else si - mi