Last active
August 29, 2015 14:16
-
-
Save anoopelias/a98859f951bd8920a9bd 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
function substring(txt, str) { | |
var dfa = compile(str); | |
var curr = 0; | |
for(var i=0; i<txt.length; i++) { | |
curr = next(dfa, curr, txt.charAt(i)); | |
if(curr === str.length) | |
return true; | |
} | |
return false; | |
} | |
function compile(str) { | |
var dfa = [[]]; | |
var chars = {}; | |
var prev = 0; | |
for(var i=0; i<str.length; i++) { | |
dfa[i] = {}; | |
if (i > 0) { | |
for(ch in chars) { | |
dfa[i][ch] = next(dfa, prev, ch); | |
} | |
prev = next(dfa, prev, str.charAt(i)); | |
} | |
// Add to a Set of all unique characters | |
chars[str.charAt(i)] = true; | |
dfa[i][str.charAt(i)] = i + 1; | |
} | |
return dfa; | |
} | |
function next(dfa, curr, ch) { | |
var next = dfa[curr][ch]; | |
if(!next) return 0; | |
return next; | |
} | |
console.log(substring('ABABABABAC', 'ABABAC')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment