【发布时间】:2013-03-08 02:20:02
【问题描述】:
我在 Java 中创建了一个 boggle 求解器,它需要大约 1 分 30 秒来求解一个棋盘,我确信它是因为我遍历字典的方式。这个想法是它检查它是否是一个单词,并查看它是否是一个有效的前缀。如果它是一个有效的前缀,它将返回 true 以便程序继续运行。如果它返回 false,那么程序将停止运行它正在学习的课程。我阅读了有关 trie 结构的信息,但我不太了解如何实现它们。带有书面代码的示例,一个小的解释将不胜感激
private ArrayList <String> dic = new ArrayList<String>(/*dictionary()*/);//my useable dictionary
private ArrayList <String> dicFinal = new ArrayList<String>();//all the words found
private ArrayList <String> checked = new ArrayList<String>();//all words that have already been checked go here
public boolean CheckTest (String word)throws IOException{//if its impossible to create a word with the combination of letters then it returns false,
String backw=reverse(word);
boolean isValid = true;
if (word.length()<=1){isValid = true;}
else if (checked.contains(word)&&checked.contains(backw)){}
else{
boolean isWord=true;
if(checked.contains(word)){}
else if(dic.contains(word)==true){
setCount(getCount()+1);
dicFinal.add(word);
dic.remove(word);
isWord=true;
}
else
isWord=false;
if(checked.contains(backw)==true){}
else if (dic.contains(backw)==true){
setCount(getCount()+1);
dicFinal.add(backw);
dic.remove(word);
}
if(isWord==false){
for(int i=0;i<dic.size();i++){
if(word.length()<=dic.get(i).length()&&dic.get(i).substring(0, word.length()).equalsIgnoreCase(word.substring(0, word.length()))){
isValid=true;
i=dic.size();
}
else
isValid=false;
}
}
}
checked.add(word);
checked.add(backw);
return isValid;
}
【问题讨论】:
-
看看
dic和checked的声明会很有价值。此外,如果您可以显示一些执行配置文件时间以确认 a)该函数实际上占用了大部分执行时间,并且 b)该函数的哪些部分占用了大部分执行时间,这将对您有所帮助我们针对最有希望的优化领域。 -
如果事实证明字典访问实际上是瓶颈,那么在 superliminal.com/sources/TrieMap.java.html 有一个 Java 中的 trie 实现。
-
它们都是arrayLists,我也不知道如何显示执行配置文件时间,因为我对Java/编程相当陌生
标签: java dictionary search solver boggle