java 实现的Boyer-Moore(BM)算法

来源:互联网 发布:梦幻西游玩着网络错误 编辑:程序博客网 时间:2024/04/29 14:03

BM算法是一种高效的单模查找算法,可以加大查找步长,效率很高, 这是java实现的版本

  1. import java.util.Arrays;
  2. import java.util.HashMap;
  3. import java.util.List;http://www.kmnk03.com/hxpfk/ylb/272.html
  4. import java.util.ArrayList;
  5. import java.util.Map;
  6. http://www.kmnk03.com/hxpfk/bdf/264.html
  7. public class BoyerMoore {
  8. public static List<Integer> match(String pattern, String text) {
  9. List<Integer> matches = new ArrayList<Integer>();
  10. int m = text.length();
  11. int n = pattern.length();
  12. Map<Character, Integer> rightMostIndexes = preprocessForBadCharacterShift(pattern);
  13. int alignedAt = 0;http://www.kmnk03.com/hxpfk/qcd/265.html
  14. while (alignedAt + (n - 1) < m) {
  15. for (int indexInPattern = n - 1; indexInPattern >= 0; indexInPattern--) {
  16. int indexInText = alignedAt + indexInPattern;
  17. char x = text.charAt(indexInText);
  18. char y = pattern.charAt(indexInPattern);
  19. if (indexInText >= m) break;
  20. if (x != y) {http://www.kmnk03.com/hxpfk/qcd/266.html
  21. Integer r = rightMostIndexes.get(x);
  22. if (r == null) {
  23. alignedAt = indexInText + 1;
  24. }
  25. else {http://www.kmnk03.com/hxpfk/pfsy/268.html
  26. int shift = indexInText - (alignedAt + r);
  27. alignedAt += shift > 0 ? shift : 1;
  28. }
  29. break;
  30. }
  31. else if (indexInPattern == 0) {
  32. matches.add(alignedAt);
  33. alignedAt++;http://www.kmnk03.com/hxpfk/ylb/271.html
  34. }
  35. }
  36. }
  37. return matches;
  38. }http://www.kmnk03.com/hxpfk/xmz/269.html
  39. private static Map<Character, Integer> preprocessForBadCharacterShift(
  40. String pattern) {
  41. Map<Character, Integer> map = new HashMap<Character, Integer>();
  42. for (int i = pattern.length() - 1; i >= 0; i--) {
  43. char c = pattern.charAt(i);
  44. if (!map.containsKey(c)) map.put(c, i);
  45. }
  46. return map;
  47. }http://www.kmnk03.com/hxpfk/qcd/267.html
  48. public static void main(String[] args) {http://www.kmnk03.com/hxpfk/tf/270.html
  49. List<Integer> matches = match("ana", "bananas");
  50. for (Integer integer : matches) System.out.println("Match at: " + integer);
  51. System.out.println((matches.equals(Arrays.asList(1, 3)) ? "OK" : "Failed"));
  52. }http://www.kmnk03.com/hxpfk/npx/273.html
  53. }kmnk03.com   www.kmnk03.com
0 0