Download code

1/* The authors of this work have released all rights to it and placed it
2 in the public domain under the Creative Commons CC0 1.0 waiver
3 (http://creativecommons.org/publicdomain/zero/1.0/).
4 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1213 Retrieved from: http://en.literateprograms.org/Boyer-Moore_string_search_algorithm_(Java)?oldid=19626
14 */151617import java.util.Arrays;18import java.util.HashMap;19import java.util.List;20import java.util.Map;21import java.util.Vector;2223publicclassBoyerMoore{24publicList<Integer>match(Stringpattern, Stringtext){25List<Integer>matches=newVector<Integer>();26intm=text.length();27intn=pattern.length();2829Map<Character, Integer>rightMostIndexes=preprocessForBadCharacterShift(pattern);30intalignedAt=0;31while(alignedAt+(n-1)<m){32for(intindexInPattern=n-1;indexInPattern>=0;indexInPattern--){33intindexInText=alignedAt+indexInPattern;34charx=text.charAt(indexInText);35chary=pattern.charAt(indexInPattern);36if(indexInText>=m)37break;38if(x!=y){39Integerr=rightMostIndexes.get(x);40if(r==null){41alignedAt=indexInText+1;42}43else{44intshift=indexInText-(alignedAt+r);45alignedAt+=shift>0 ? shift:alignedAt+1;46}47break;48}49elseif(indexInPattern==0){50matches.add(alignedAt);51alignedAt++;52}53}54}55returnmatches;56}57privateMap<Character, Integer>preprocessForBadCharacterShift(58Stringpattern){59Map<Character, Integer>map=newHashMap<Character, Integer>();60for(inti=pattern.length()-1;i>=0;i--){61charc=pattern.charAt(i);62if(!map.containsKey(c))map.put(c, i);63}64returnmap;65}66publicstaticvoidmain(String[]args){67List<Integer>matches=newBoyerMoore().match("ana", "bananas");68for(Integerinteger:matches)System.out.println("Match at: "+integer);69System.out.println((matches.equals(Arrays.asList(1, 3)) ? "OK":"Failed"));70}71}