Created
October 27, 2013 04:53
-
-
Save gmenard/7178113 to your computer and use it in GitHub Desktop.
Boyer–Moore string search algorithm.
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
/** | |
* 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