错误的布尔赋值 - anagrams算法

时间:2015-11-03 19:02:49

标签: java

我知道你可能知道更好更快的方式,但是请原谅 - 我正在学习......

我的问题是这个方法应该......但不能用我现在的代码...返回布尔值" anagram"如果特定单词的所有选中字母都出现在第二个列表中的检查单词中,则为TRUE

我的布尔值仍然是最后一个检查过的字母状态,请帮忙。

for (String aWord : aWordsList){ //main List positions loop
                    tempWordsList = new ArrayList<String>(aWordsList);;

//set anagram TRUE if all letters of examined word found in temp List
                boolean anagram = true; 
                    for (int a=0; a<tempWordsList.size(); a++){ //temp List word loop
                    anagram = true;
                        for (int i=0; i<aWord.length(); i++){ //main List word Letters loop
                            anagram = true;
                            boolean letterFound = true;

                            for (int letter=0; letter < tempWordsList.get(a).length(); letter++){ //temp List word Letters loop

                                anagram = true;
                                String checkedTempWord = tempWordsList.get(a);
                                char checkedLetter = aWord.charAt(i);
                                char checkedTempLetter = tempWordsList.get(a).charAt(letter);

                                    if (aWord.charAt(i)==tempWordsList.get(a).charAt(letter)){
                                        letterFound = true;
                                        break;
                                        // OK, jump out and check next letter
                                    }else{
                                        letterFound= false;
                                    }

                            }
                            if (anagram == true && letterFound==true) {
                                anagram=true;
                            }else{
                                anagram=false;
                            }
                            System.out.println(aWord +" in "+ tempWordsList.get(a) + " : " + aWord.charAt(i) + " " + letterFound); 

                        }
                        System.out.println(aWord + " has anagram in " + tempWordsList.get(a) + ": " + anagram);
                        System.out.println();
                    }
                    System.out.println(aWord + " " + tempWordsList + " " + anagram);
                }
            }


        }

1 个答案:

答案 0 :(得分:0)

我想我发现了错误:anagram设置为true的次数太多了...... 这段代码看起来对我有用:

//set anagram TRUE if all letters of examined word found in temp List
            boolean anagram = true;
                for (int a=0; a<tempWordsList.size(); a++){ //temp List word loop
                anagram = true;
                    for (int i=0; i<aWord.length(); i++){ //main List word Letters loop
                        //anagram = true;
                        boolean letterFound = true;

                        for (int letter=0; letter < tempWordsList.get(a).length(); letter++){ //temp List word Letters loop

                            //anagram = true;