1 2 3 4 package net.nutch.util; 5 6 import java.util.Collection ; 7 import java.util.Iterator ; 8 9 13 public class PrefixStringMatcher extends TrieStringMatcher { 14 15 20 public PrefixStringMatcher(String [] prefixes) { 21 super(); 22 for (int i= 0; i < prefixes.length; i++) 23 addPatternForward(prefixes[i]); 24 } 25 26 34 public PrefixStringMatcher(Collection prefixes) { 35 super(); 36 Iterator iter= prefixes.iterator(); 37 while (iter.hasNext()) 38 addPatternForward((String )iter.next()); 39 } 40 41 45 public boolean matches(String input) { 46 TrieNode node= root; 47 for (int i= 0; i < input.length(); i++) { 48 node= node.getChild(input.charAt(i)); 49 if (node == null) 50 return false; 51 if (node.isTerminal()) 52 return true; 53 } 54 return false; 55 } 56 57 61 public String shortestMatch(String input) { 62 TrieNode node= root; 63 for (int i= 0; i < input.length(); i++) { 64 node= node.getChild(input.charAt(i)); 65 if (node == null) 66 return null; 67 if (node.isTerminal()) 68 return input.substring(0, i+1); 69 } 70 return null; 71 } 72 73 77 public String longestMatch(String input) { 78 TrieNode node= root; 79 String result= null; 80 for (int i= 0; i < input.length(); i++) { 81 node= node.getChild(input.charAt(i)); 82 if (node == null) 83 break; 84 if (node.isTerminal()) 85 result= input.substring(0, i+1); 86 } 87 return result; 88 } 89 90 public static final void main(String [] argv) { 91 PrefixStringMatcher matcher= 92 new PrefixStringMatcher( 93 new String [] 94 {"abcd", "abc", "aac", "baz", "foo", "foobar"} ); 95 96 String [] tests= {"a", "ab", "abc", "abcdefg", "apple", "aa", "aac", 97 "aaccca", "abaz", "baz", "bazooka", "fo", "foobar", 98 "kite", }; 99 100 for (int i= 0; i < tests.length; i++) { 101 System.out.println("testing: " + tests[i]); 102 System.out.println(" matches: " + matcher.matches(tests[i])); 103 System.out.println(" shortest: " + matcher.shortestMatch(tests[i])); 104 System.out.println(" longest: " + matcher.longestMatch(tests[i])); 105 } 106 } 107 } 108 | Popular Tags |