没有找到Trie排列

时间:2012-03-15 23:06:11

标签: java android dictionary trie

我在使用Java中的Trie进行anagram解算器时遇到了问题。以下代码适用于Android,并没有给出任何给定和传入的字母的排列结果。但是,如果我在Java桌面应用程序中实现相同的代码,它将为我返回正确的结果。我很确定这是一个简单的错误,我似乎无法找到它。

桌面版代码:

static String myWord;
    static String myLetters = "";
    static char[] myChars;
    static TrieNode myNode = new TrieNode();
    static TrieNode currentNode;
    static ArrayList<String> availableWords = new ArrayList<String>();

    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);
        myLetters = s.next();

        readWords();
        getPermutations();
    }
    public static void getPermutations(){
        currentNode = myNode;
        for(int x = 0; x < myLetters.length(); x++){
            if(currentNode.children[myLetters.charAt(x) - 'a'] != null){
                availableWords.addAll(currentNode.getWords());
                currentNode = currentNode.children[myLetters.charAt(x) - 'a'];
                System.out.println("x: " + x + " " + currentNode.getWords() + "" + myLetters.charAt(x));
            }
        }   
        System.out.println(availableWords);
    }

Desktop Output:
aelpp  //(user input from scanner)
x: 0 []a
x: 1 [ae]e
x: 2 [ale, lea]l
x: 3 [leap, pale, peal, plea]p
x: 4 [appel, apple, pepla]p
[ae, ale, lea, leap, pale, peal, plea] 

Android代码:

static String myWord;
    static char[] myChars;
    static TrieNode myNode = new TrieNode();
    static TrieNode currentNode;
    static ArrayList<String> availableWords = new ArrayList<String>();

    public static void getPermutations(String passedInLetters){
        currentNode = myNode;
        Log.i("TRIE:" , passedInLetters);
        for(int x = 0; x < passedInLetters.length(); x++){
            if(currentNode.children[passedInLetters.charAt(x) - 'a'] != null){
                availableWords.addAll(currentNode.getWords());
                Log.i("TRIE:" , "x: " + x + " " + currentNode.getWords());
                currentNode = currentNode.children[passedInLetters.charAt(x) - 'a'];
            }
        }
        Log.i("TRIE:", availableWords.toString());
    }

Android日志输出:

03-15 22:45:11.670: I/TRIE:(4286): aelpp
03-15 22:45:11.670: I/TRIE:(4286): x: 0 []
03-15 22:45:11.670: I/TRIE:(4286): x: 1 []
03-15 22:45:11.670: I/TRIE:(4286): x: 2 []
03-15 22:45:11.670: I/TRIE:(4286): x: 3 []
03-15 22:45:11.670: I/TRIE:(4286): x: 4 []
03-15 22:45:11.670: I/TRIE:(4286): []

如果需要,以下是完整的课程:

桌面:http://pastie.org/3604515 Android:http://pastie.org/3604513

我在其他一些资料中研究过这篇文章:java string permutations and combinations lookup

谢谢!

编辑:

这些行需要在if语句中切换:

currentNode = currentNode.children[passedInLetters.charAt(x) - 'a'];
                availableWords.addAll(currentNode.getWords());

0 个答案:

没有答案