// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.
// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.
function kmpSearch(pattern, text) {
if (pattern.length == 0)
return 0; // Immediate match
// Compute longest suffix-prefix table
var lsp = [0]; // Base case
for (var i = 1; i < pattern.length; i++) {
var j = lsp[i - 1]; // Start by assuming we're extending the previous LSP
while (j > 0 && pattern.charAt(i) != pattern.charAt(j))
j = lsp[j - 1];
if (pattern.charAt(i) == pattern.charAt(j))
j++;
lsp.push(j);
}
// Walk through text string
var j = 0; // Number of chars matched in pattern
for (var i = 0; i < text.length; i++) {
while (j > 0 && text.charAt(i) != pattern.charAt(j))
j = lsp[j - 1]; // Fall back in the pattern
if (text.charAt(i) == pattern.charAt(j)) {
j++; // Next char matched, increment position
if (j == pattern.length)
return i - (j - 1);
}
}
return -1; // Not found
}
console.log(kmpSearch('ays', 'haystack') != -1) // true
console.log(kmpSearch('asdf', 'haystack') != -1) // false
3条答案
按热度按时间mu0hgdu01#
介绍了ecmascript 6
String.prototype.includes
:var string = "foo";
var substring = "oo";
console.log(string.indexOf(substring) !== -1);
rpppsulh2#
有一个
String.prototype.includes
在es6中:请注意,这在internet explorer或其他不支持es6或es6不完整的旧浏览器中不起作用。要使其在旧浏览器中工作,您可能希望使用诸如babel之类的transpiler、诸如es6 shim之类的shim库或mdn中的polyfill:
tyky79it3#
另一种选择是kmp(克努特-莫里斯-普拉特)。
kmp算法在最坏情况下的o(n+m)时间内搜索长度为n的字符串中的长度为m的子字符串,而在最坏情况下的o(n)时间内搜索长度为n的字符串⋅m) 对于naive算法,如果您关心最坏情况下的时间复杂度,那么使用kmp可能是合理的。
下面是nayuki项目的javascript实现,摘自https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js: