Skip to content

Instantly share code, notes, and snippets.

@gmenard
Created October 27, 2013 04:53
Show Gist options
  • Save gmenard/7178113 to your computer and use it in GitHub Desktop.
Save gmenard/7178113 to your computer and use it in GitHub Desktop.
Boyer–Moore string search algorithm.
/**
* Search if a string (pattern) is contained in another string (text)
* according to the Boyer–Moore string search algorithm.
*
* @param pattern string to search for
* @param text string to search in
* @return true if text contains pattern, otherwise false
*/
public static Boolean search(String pattern, String text) {
if (null == pattern || pattern.isEmpty()) return false;
if (null == text || text.isEmpty()) return false;
if (pattern.length() > text.length()) return false;
int textLength = text.length();
int patternLength = pattern.length();
int textIndex = patternLength - 1;
int patternIndex = patternLength - 1;
while (textIndex < textLength) {
if (pattern.charAt(patternIndex) == text.charAt(textIndex)) {
if (patternIndex == 0) return true;
textIndex--;
patternIndex--;
} else {
textIndex += patternLength - Math.min(patternIndex, textLength + 1);
patternIndex = patternLength - 1;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment