如何用JavaScrpit实现KMP算法
时间: 2024-05-14 19:14:57 浏览: 80
KMP算法是一种字符串匹配算法,可以用JavaScript实现。以下是一个基本的KMP算法实现:
```
function KMP(pattern, text) {
let i = 0;
let j = 0;
const patternLength = pattern.length;
const textLength = text.length;
const table = buildTable(pattern);
while (i < textLength) {
if (pattern[j] === text[i]) {
i++;
j++;
}
if (j === patternLength) {
return i - j;
} else if (i < textLength && pattern[j] !== text[i]) {
if (j !== 0) {
j = table[j - 1];
} else {
i++;
}
}
}
return -1;
}
function buildTable(pattern) {
const patternLength = pattern.length;
const table = Array(patternLength).fill(0);
let i = 0;
let j = 1;
while (j < patternLength) {
if (pattern[i] === pattern[j]) {
i++;
table[j] = i;
j++;
} else {
if (i !== 0) {
i = table[i - 1];
} else {
table[j] = 0;
j++;
}
}
}
return table;
}
```
使用方法:
```
const text = 'ababcabcabababd';
const pattern = 'ababd';
const position = KMP(pattern, text);
console.log(position);
```
输出:
```
10
```
这表示在文本中找到了模式的位置,从0开始计数。
阅读全文