BM算法是一种高效的单模查找算法,可以加大查找步长,效率很高, 这是java实现的版本
- import java.util.Arrays;
- import java.util.HashMap;
- import java.util.List;http://www.kmnk03.com/hxpfk/ylb/272.html
- import java.util.ArrayList;
- import java.util.Map;
- http://www.kmnk03.com/hxpfk/bdf/264.html
- 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;http://www.kmnk03.com/hxpfk/qcd/265.html
- 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) {http://www.kmnk03.com/hxpfk/qcd/266.html
- Integer r = rightMostIndexes.get(x);
- if (r == null) {
- alignedAt = indexInText + 1;
- }
- else {http://www.kmnk03.com/hxpfk/pfsy/268.html
- int shift = indexInText - (alignedAt + r);
- alignedAt += shift > 0 ? shift : 1;
- }
- break;
- }
- else if (indexInPattern == 0) {
- matches.add(alignedAt);
- alignedAt++;http://www.kmnk03.com/hxpfk/ylb/271.html
- }
- }
- }
- return matches;
- }http://www.kmnk03.com/hxpfk/xmz/269.html
- 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;
- }http://www.kmnk03.com/hxpfk/qcd/267.html
- public static void main(String[] args) {http://www.kmnk03.com/hxpfk/tf/270.html
- 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"));
- }http://www.kmnk03.com/hxpfk/npx/273.html
- }kmnk03.com www.kmnk03.com
0 0