Java - 迭代 ArrayList 并查找 Anagrams

Java - Iterate an ArrayList and Find Anagrams

我有一个排序的规范词列表,我想用迭代器迭代列表以找到匹配的规范词,这些词将具有相同的字谜,然后将它们添加到一个单独的 LinkedList 中,如果它们匹配则配对在一起。我该怎么做呢?我会 运行 一次为同一个列表使用两个迭代器,并将它们放入嵌套的 while 循环中,第一个元素上有一个迭代器,第二个迭代器在同一列表中搜索所有元素以进行匹配,然后将其添加到列表中如果找到匹配项?有什么想法吗?

这是我到目前为止所做的:

驱动程序Class文件:

import java.util.*;
import java.io.*;

public class Programming9Driver {

   public static void main(String[] theArgs) {
      LinkedList<Word> wordObjects = new LinkedList<Word>();
      ArrayList<String> localWords = new ArrayList<String>();
      BufferedReader localInput = null;
      BufferedWriter localOutput = null;


      try {
         String localLine;
         localInput = new BufferedReader(new FileReader("words.txt"));
//         localOutput = new BufferedWriter(new FileWriter("out9.txt"));
         while ((localLine = localInput.readLine()) != null) {
            if (localLine != "") {
            localWords.add(localLine);
            }
//          
//         
         }
/*
*/
         localInput.close();
//       localOutput.close();
      } catch (Exception e) {
         System.out.println("Difficulties opening the file! " + e);
         System.exit(1);
      }

      localWords.removeAll(Collections.singleton(""));
      Map<String, List<String>> anagramList = new HashMap<String, List<String>>();
      Iterator<String> iterAdd = localWords.iterator();

      while (iterAdd.hasNext()) {
         wordObjects.add(new Word(iterAdd.next()));   
      }
      Collections.sort(wordObjects);

      LinkedList<AnagramFamily> anagramObjects = new LinkedList<AnagramFamily>();

  }       
}

Word.java:

import java.util.*;

public class Word implements Comparable<Word>{

   private String myWord;

   private String myCanon;

   private Map<String, List<String>> myCanonKey = new HashMap<String, List<String>>();

   public Word(final String theWord) { 
      myWord = theWord;
      myCanon = canonForm();
      myCanonKey = canonWords();    
   }

   public String canonForm() {
      String canonWord = "";
      Character[] localChars = new Character[myWord.length()];

      for (int i = 0; i < localChars.length; i++) {
         localChars[i] = myWord.charAt(i);
      }

      Arrays.sort(localChars);

      for (int i = 0; i < localChars.length; i++) {
         canonWord += localChars[i];
      }
      return canonWord;         
   }

   public Map<String, List<String>> canonWords() {
      ArrayList<String> canonList = new ArrayList<String>();
      Map<String, List<String>> canonKey = new HashMap<String, List<String>>();
      canonList.add(myWord);
      canonKey.put(myCanon, canonList);
      return canonKey;
   }

   public int compareTo(Word theOther) {
      int result = canonForm().compareTo(theOther.canonForm());
      return result;
   }

   public String toString() {
      String result = "";
      result = myWord;
      if (myWord == "" || myCanon == "") {
         result = "";
      }
      return result;
   }        
}

如何从我的主驱动程序调用以使用 Word class java 文件中的 canonWords() 方法?

一种解决方法是遍历所有字符串,从原始字符串的按字母顺序排序的 char 数组创建一个新字符串,并将新字符串用作 Map<String, List<String>> 中的键。

编辑:老实说,您发布的代码似乎有点过头了。这是我的想法的演示:

Collection<LinkedList<String>> groupAnagrams(List<String> words) {
    Map<String, LinkedList<String>> anagramMap = new HashMap<>();
    for(String word : words) {
        char[] wordChars = word.toCharArray();
        Arrays.sort(wordChars);
        String sortedKey = new String(wordChars);
        LinkedList<String> anagramList = anagramMap.get(sortedKey);
        if(anagramList == null) {
            anagramMap.put(sortedKey, anagramList = new LinkedList<>());
        }
        anagramList.add(word);
    }
    return anagramMap.values();
}

编辑 2: 只是为了好玩,这是一个 Java 8 实现:

Collection<List<String>> groupAnagrams(List<String> words) {
    return words.stream().collect(groupingBy(w -> {
                char[] chars = w.toCharArray();
                Arrays.sort(chars);
                return new String(chars);
            })).values();
}