Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

updated the kmp from es5->es6 #214

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 31 additions & 34 deletions src/searching/knuth-morris-pratt.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
(function (exports) {
'use strict';

var kmp = (function () {
function builtKMPTable(str) {
var res = [];
var len;
var front;
var end;
var found;
for (var i = 1; i <= str.length; i += 1) {
const kmp = (str, substr) => {
if (str === substr) {
return 0;
}
const builtKMPTable = (str) => {
const res = [];
let len;
let front;
let end;
let found;
for (let i = 1; i <= str.length; i += 1) {
front = Math.max(1, i - ((res[i - 2] || 0) + 1));
end = Math.min(i - 1, (res[i - 2] || 0) + 1);
found = false;
Expand All @@ -25,7 +28,7 @@
res[i - 1] = len;
}
return res;
}
};

/**
* Knuth–Morris–Pratt algorithm. Searches for the position of
Expand All @@ -45,35 +48,29 @@
* where the specified substring occurs for the first
* time, or -1 if it never occurs.
*/
function indexOf(str, substr) {
if (str === substr) {
return 0;

const table = builtKMPTable(substr);
let i = 0;
let j = 0;
while (i < str.length) {
if (str[i] === substr[j]) {
i += 1;
j += 1;
}
var table = builtKMPTable(substr);
var i = 0;
var j = 0;
while (i < str.length) {
if (str[i] === substr[j]) {
if (j === substr.length) {
return i - j;
}
if (i < str.length && str[i] !== substr[j]) {
if (j > 0 && table[j - 1] !== 0) {
j = table[j - 1];
} else {
i += 1;
j += 1;
}
if (j === substr.length) {
return i - j;
}
if (i < str.length && str[i] !== substr[j]) {
if (j > 0 && table[j - 1] !== 0) {
j = table[j - 1];
} else {
i += 1;
j = 0;
}
j = 0;
}
}
return -1;
}
return indexOf;
}());

return -1;
};
exports.kmp = kmp;

})(typeof window === 'undefined' ? module.exports : window);