Skip to content

Instantly share code, notes, and snippets.

@stanley-shi
Created July 23, 2014 08:20
Show Gist options
  • Save stanley-shi/41409a581fd737b5971b to your computer and use it in GitHub Desktop.
Save stanley-shi/41409a581fd737b5971b to your computer and use it in GitHub Desktop.
Search for a string from a stream
public static class MyInt {
public MyInt(int i) {
data = i;
}
int data;
}
public static long getFirstIndex(String str, InputStream is)
throws IOException {
byte[] bstr = str.getBytes();
Set<MyInt> matches = new HashSet<MyInt>();
Set<MyInt> toRemove = new HashSet<MyInt>();
int pos = 0;
while (is.available() > 0) {
int data = is.read();
pos++;
if (matches.size() > 0) {
// has a previous match
for (MyInt i : matches) {
if (data == bstr[i.data + 1]) {
i.data++;
if (i.data == bstr.length - 1) {
// matches!!!
return pos - bstr.length;
}
} else
toRemove.add(i);
}
matches.removeAll(toRemove);
toRemove.clear();
}
if (data == bstr[0]) {
matches.add(new MyInt(0));
}
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment