如果可以从较小的关键字构建关键字,那么您对有效代码所做的一切就是首先检查较长的关键字。请注意:我根本没有测试这个,我想我已经在这个问题上做了足够的工作!如果这对您有帮助,请不要忘记投票+接受。
IE
import java.util.TreeSet;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.HashMap;
import java.util.Iterator;
public class KeywordSearcher {
private TreeSet<String> ts;
public KeywordSearcher() {
ts = new TreeSet<String>(new Comparator<String>() {
// Sort all the keywords by length, largest first
public int compare(String arg0, String arg1) {
if(arg0.length() > arg1.length()) return -1;
if(arg0.length() == arg1.length()) return 0;
return 1;
}});
}
public void addKeyword(String s) {
ts.add(s);
}
private LinkedList<Integer> findKeyword(String document, String s) {
int start = 0;
int index;
LinkedList<Integer> indexes = new LinkedList<Integer>();
while(true) {
index = document.indexOf(s, start);
if (index == -1) break;
indexes.add(index);
start = index + s.length();
}
return indexes;
}
public HashMap<String, LinkedList<Integer>> findAllKeywords(String document) {
Iterator<String> is = ts.iterator();
HashMap<String, LinkedList<Integer>> allIndices = new HashMap<String, LinkedList<Integer>>();
while(is.hasNext()) {
String nextKeyword = is.next();
// See if we found a larger keyword, if we did already, skip this keyword
boolean foundIt = false;
for (String key : allIndices.keySet()) {
if(key.contains(nextKeyword)) {
foundIt = true;
break;
}
}
if (foundIt) continue;
// We didn't find the larger keyword, look for the smaller keyword
LinkedList<Integer> indexes = findKeyword(document, nextKeyword);
if (indexes.size() > 0) allIndices.put(nextKeyword, indexes);
}
return allIndices;
}
}