Last active
August 29, 2015 13:57
-
-
Save noblethrasher/9516631 to your computer and use it in GitHub Desktop.
IsSubstring
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
class SubstringRecognition | |
{ | |
readonly string s; | |
int state = 0; | |
int pos = 0; | |
Func<char, SubstringRecognition>[] accept; | |
public bool Found | |
{ | |
get | |
{ | |
return pos >= s.Length; | |
} | |
} | |
public SubstringRecognition(string s) | |
{ | |
this.s = s; | |
accept = new[] { (Func<char, SubstringRecognition>)_Accept0, _Accept1 }; | |
} | |
SubstringRecognition _Accept0(char c) | |
{ | |
if (c == s[0]) | |
{ | |
state = 1; | |
pos++; | |
} | |
return this; | |
} | |
SubstringRecognition _Accept1(char c) | |
{ | |
if (pos >= s.Length) | |
return this; | |
if (c != s[pos]) | |
{ | |
state = 0; | |
pos = 0; | |
return _Accept0(c); | |
} | |
else | |
pos++; | |
return this; | |
} | |
public SubstringRecognition Accept(char c) | |
{ | |
return accept[state](c); | |
} | |
} | |
static class Utils | |
{ | |
static bool IsSubstring(this string s, string t) | |
{ | |
if (s == null || t == null || (s.Length > t.Length)) | |
return false; | |
var recog = new SubstringRecognition(s); | |
for (var i = 0; i < t.Length; i++) | |
recog = recog.Accept(t[i]); | |
return recog.Found; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment