@@ -0,0 +1,2095 @@
+package org.karticks.coding;%0A%0Aimport java.util.ArrayList;%0Aimport java.util.Arrays;%0Aimport java.util.Collection;%0Aimport java.util.Hashtable;%0Aimport java.util.Scanner;%0A%0A/*%0A * Given a list of words, detect which ones are anagrams.%0A * Input is specified in the following format :%0A * N is the number of input words (first line of input)%0A * N lines with a word on each line%0A * %0A * For example :%0A * 6%0A * pans%0A * pots%0A * opt%0A * snap%0A * stop%0A * tops%0A * %0A */%0Apublic class AnagramDetector%0A%7B%0A%09public static void main(String%5B%5D args)%0A%09%7B%0A%09%09try%0A%09%09%7B%0A%09%09%09Scanner scanner = new Scanner(System.in);%0A%09%09%09%0A%09%09%09int numWords = Integer.parseInt(scanner.nextLine());%0A%09%09%09%0A%09%09%09Hashtable%3CString, ArrayList%3CString%3E%3E table = new Hashtable%3CString, ArrayList%3CString%3E%3E();%0A%09%09%09for (int i = 0; i %3C numWords; i++)%0A%09%09%09%7B%0A%09%09%09%09String s = scanner.nextLine();%0A%09%09%09%09%0A%09%09%09%09handleWord(s, table);%0A%09%09%09%7D%0A%09%09%09%0A%09%09%09scanner.close();%0A%09%09%09%0A%09%09%09printAnagrams(table.values());%0A%09%09%09%0A%09%09%7D%0A%09%09catch (Exception e)%0A%09%09%7B%0A%09%09%09System.out.println(%22Caught an exception. Error message : %22 + e.getMessage());%0A%09%09%09e.printStackTrace();%0A%09%09%7D%0A%09%7D%0A%09%0A%09// most of the dirty work in breaking strings into chars, sorting the chars, and rebuilding%0A%09// the sorted string from the (sorted) chars%0A%09// Once we have the sorted string, we add it to the hashtable (do the requisite check to see if%0A%09// exists ornot) and add the original word to a list (the value)%0A%09private static void handleWord(String s, Hashtable%3CString, ArrayList%3CString%3E%3E table)%0A%09%7B%0A%09%09char%5B%5D chars = s.toCharArray();%0A%09%09Arrays.sort(chars);%0A%09%09%0A%09%09String key = new String(chars);%0A%09%09%0A%09%09ArrayList%3CString%3E values;%0A%09%09if (table.containsKey(key))%0A%09%09%7B%0A%09%09%09values = table.get(key);%0A%09%09%7D%0A%09%09else%0A%09%09%7B%0A%09%09%09values = new ArrayList%3CString%3E();%0A%09%09%7D%0A%09%09values.add(s);%0A%09%09table.put(key, values);%0A%09%7D%0A%09%0A%09private static void printAnagrams(Collection%3CArrayList%3CString%3E%3E values)%0A%09%7B%0A%09%09for (ArrayList%3CString%3E al : values)%0A%09%09%7B%0A%09%09%09// if there is more than one entry in the list, then we have at least a pair of anagrams%0A%09%09%09if (al.size() %3E 1)%0A%09%09%09%7B%0A%09%09%09%09System.out.println(%22*************%22);%0A%09%09%09%09for (String s : al)%0A%09%09%09%09%7B%0A%09%09%09%09%09System.out.println(s);%0A%09%09%09%09%7D%0A%09%09%09%7D%0A%09%09%7D%0A%09%7D%0A%7D%0A

Given a list of strings, detect anagrams