Last active
October 30, 2018 13:15
-
-
Save xxjinwei/c57c0dbf4c6a4df66376ac3bb9422990 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
参考:KMP字符串匹配算法