文章 评论 浏览 29
搜索了一下KMP算法:https://zh.wikipedia.org/wiki/%E5%85%8B%E5%8A%AA%E6%96%AF-%E8%8E%AB%E9%87%8C%E6%96%AF-%E6%99%AE%E6%8B%89%E7%89%B9%E7%AE%97%E6%B3%95
// 应该...没有bug吧^^ function getIndex (S, T) { const n = S.length; const m = T.length; if (n < m) { return -1; } if (n === m) { return S === T ? 0 : -1; } const start = T[0]; const end = T[m - 1]; let i = 0; while (i < n) { if (n - i < m) { return -1; } const currS = S[i]; const currSEnd = S[i + m - 1]; let mathing = true; if (currS !== start || currSEnd !== end) { i++; continue; } let j = 0; let step = 0; while (j < m) { const currS = S[i + j]; const currSEnd = S[i + j + m - 1]; const isEnd = j === m - 1; if (mathing) { const currW = T[j]; mathing = currS === currW; if (mathing && isEnd) { return i } } if (!mathing && step !== 0) { break; } if (j > 0 && step === 0) { if (isEnd) { step = m; } if (currS === start && currSEnd === end) { step = j; } } j++; } i += step || 1; } return -1; }
文章 0 评论 0
接受
搜索了一下KMP算法:
https://zh.wikipedia.org/wiki/%E5%85%8B%E5%8A%AA%E6%96%AF-%E8%8E%AB%E9%87%8C%E6%96%AF-%E6%99%AE%E6%8B%89%E7%89%B9%E7%AE%97%E6%B3%95
第 71 题: 实现一个字符串匹配算法,从长度为 n 的字符串 S 中,查找是否存在字符串 T,T 的长度是 m,若存在返回所在位置