美文网首页
kmp 算法

kmp 算法

作者: 健健锅 | 来源:发表于2019-01-14 11:38 被阅读4次
     //https://blog.csdn.net/x__1998/article/details/79951598
        func gethexLong(_ str :String) -> [Int] {
            var next :[Int] = []
            
            for i  in 0..<str.count {
    
                let strItme = str.getStringRangeStr(0, i)
                print(strItme)
                if(i == 0){
                    next.append(0)
                }else{
                    let lastLength = next[i - 1]
                    let lastStr = strItme.getStringChar(strItme.count - 1)//最后字符
                    let firstStr = strItme.getStringChar(lastLength)//第一个字符
                    if(lastStr == firstStr){
                       
                        next.append(lastLength + 1)
                    }else{
                        let PfirstStr = strItme.getStringChar(0)//第一个字符
                        if(lastStr == PfirstStr){
                            next.append(1)
                        }else{
                            next.append(0)
                        }
                    }
                }
            }
             print(next)
            return next
        }
        
        func kmp(_ mainStr :String ,_ pStr :String) -> Bool {
           
         let next = self.gethexLong(pStr)
            var j = 0
            var count = 0 //一共可以匹配的字符串个数
            for  i  in 0..<mainStr.count{
                
                let str  = mainStr.getStringChar(i)
                var strp = pStr.getStringChar(j)
                while str != strp{
                    let lastCount = next[j-1]
                    j = lastCount
                    strp = pStr.getStringChar(j)
                }
    
                    if j == pStr.count - 1{
                        count += 1
                        return true
                    }else{
                        j += 1
                    }
            }
            return false
        }
    

    相关文章

      网友评论

          本文标题:kmp 算法

          本文链接:https://www.haomeiwen.com/subject/uosddqtx.html