简体   繁体   中英

Making my dictionary search more efficient

I created a boggle solver in Java and it takes around a minute and 30 seconds to solve a board and I'm convinced its because of the way I traverse through my dictionary. The idea is it checks to see if its a word and also to see if it is a valid prefix. if its a valid prefix it will return true so the program continues running. If it returns false then the program will stop running the course it is taking. I read about trie structures but I don't quite get how to implement them. Examples with written code a small explanation would be most appreciated

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;
}

I'd suggest that the first thing to do would be to make dic and checked HashSets instead of ArrayLists, which will give you O(1) access time instead of O(N). If your supposition that these lookups are the key bottleneck is correct, your program's performance should improve enormously.

If that doesn't improve matters enough, it would be worth investing a few minutes in learning how to profile Java programs so that you can pinpoint where the problem lies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM