java 实现的Boyer-Moore(BM)算法
2018-07-20 来源:open-open
BM算法是一种高效的单模查找算法,可以加大查找步长,效率很高, 这是java实现的版本
import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Map; public class BoyerMoore { public static List<Integer> match(String pattern, String text) { List<Integer> matches = new ArrayList<Integer>(); int m = text.length(); int n = pattern.length(); Map<Character, Integer> rightMostIndexes = preprocessForBadCharacterShift(pattern); int alignedAt = 0; while (alignedAt + (n - 1) < m) { for (int indexInPattern = n - 1; indexInPattern >= 0; indexInPattern--) { int indexInText = alignedAt + indexInPattern; char x = text.charAt(indexInText); char y = pattern.charAt(indexInPattern); if (indexInText >= m) break; if (x != y) { Integer r = rightMostIndexes.get(x); if (r == null) { alignedAt = indexInText + 1; } else { int shift = indexInText - (alignedAt + r); alignedAt += shift > 0 ? shift : 1; } break; } else if (indexInPattern == 0) { matches.add(alignedAt); alignedAt++; } } } return matches; } private static Map<Character, Integer> preprocessForBadCharacterShift( String pattern) { Map<Character, Integer> map = new HashMap<Character, Integer>(); for (int i = pattern.length() - 1; i >= 0; i--) { char c = pattern.charAt(i); if (!map.containsKey(c)) map.put(c, i); } return map; } public static void main(String[] args) { List<Integer> matches = match("ana", "bananas"); for (Integer integer : matches) System.out.println("Match at: " + integer); System.out.println((matches.equals(Arrays.asList(1, 3)) ? "OK" : "Failed")); } }
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
最新资讯
热门推荐