Skip to content

Instantly share code, notes, and snippets.

@jimmyFlash
Created January 7, 2020 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimmyFlash/acb8766fbf580fc331ae03b110fc2060 to your computer and use it in GitHub Desktop.
Save jimmyFlash/acb8766fbf580fc331ae03b110fc2060 to your computer and use it in GitHub Desktop.
solving anagrams, print anagrams and non-anagrams in sorted matter
import java.util.*;
import java.util.stream.Collectors;
public class Anagrams {
private static String[] anagrams = {
"pear",
"amleth",
"dormitory",
"tinsel",
"dirty room",
"hamlet",
"door me try",
"listen"};
public static void main(String[] args) {
int size = anagrams.length;
printAnagramsUsingHashmap(anagrams);
}
/**
* solution using hashmaps
* @param arr array of strings containing anagrams
*/
private static void printAnagramsUsingHashmap(String[] arr) {
System.out.println("--Solution start >>>>>>>> ");
HashMap<String, List<String>> map = new HashMap<>();
System.out.println("serialized array: " + String.join(",", arr) + "\n");
// loop over all words
for (String word : arr) {
String removeWhiteSpace = word.replaceAll("\\s", "");// remove spaces within a word
// convert to char array, sort and
// then re-convert to string
char[] letters = removeWhiteSpace.toCharArray();
Arrays.sort(letters);
String newWord = new String(letters);
// calculate hashcode of string
// after sorting
if (map.containsKey(newWord)) {
map.get(newWord).add(word);
} else {
// This is the first time we are
// adding a word for a specific
// hashcode
List<String> words = new ArrayList<>();
words.add(word);
map.put(newWord, words);
}
}
// Now let's sort HashMap by keys first
// all you need to do is create a TreeMap with mappings of HashMap
// TreeMap keeps all entries in sorted order
TreeMap<String, List<String>> sorted = new TreeMap<>(map);
Set<Map.Entry<String, List<String>>> mappings = sorted.entrySet();
for(Map.Entry<String, List<String>> mapping : mappings){
// System.out.println(mapping.getKey() + " ==> " + mapping.getValue());
if (mapping.getValue().size() > 1) { // anagrams
System.out.println("anagrams: " + mapping.getValue().toString().replaceAll("[\\[\\]]", ""));
} else if (mapping.getValue().size() == 1) {// non-anagrams
System.out.println("non-anagrams: " + mapping.getValue().toString().replaceAll("[\\[\\]]", ""));
}
}
System.out.println("--Solution end <<<<<<< ");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment