Skip to content

Instantly share code, notes, and snippets.

@xxjinwei
Last active October 30, 2018 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xxjinwei/c57c0dbf4c6a4df66376ac3bb9422990 to your computer and use it in GitHub Desktop.
Save xxjinwei/c57c0dbf4c6a4df66376ac3bb9422990 to your computer and use it in GitHub Desktop.
const getNext = str => {
let len = str.length;
let next = [-1];
let i = 0;
let p = -1;
while (i < len) {
if (p === -1 || str[i] === str[p]) {
next[++i] = ++p;
} else {
p = next[p];
}
}
return next;
};
const strStr = (str, patten) => {
if (patten === "") {
return 0;
}
let next = getNext(patten);
let m = str.length;
let n = patten.length;
let i = 0;
let j = 0;
while (i < m && j < n) {
if (j === -1 || str[i] === patten[j]) {
i++;
j++;
} else {
j = next[j];
}
}
return j === n ? i - j : -1;
};
@xxjinwei
Copy link
Author

@xxjinwei
Copy link
Author

leetcode #28

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment