Last active
July 1, 2017 00:05
-
-
Save rafaelvcaetano/a20ccd24d768aec62614e331588c3770 to your computer and use it in GitHub Desktop.
Function to find anagrams in a list of words
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.Collections; | |
import java.util.HashMap; | |
import java.util.LinkedList; | |
public class AnagramFinder { | |
public static void main(String[] args) { | |
for (String s : findAnagrams(args)) { | |
System.out.println(s); | |
} | |
} | |
/** | |
* Given an array of words, find word pairs that are anagrams. | |
* @param input The list of words | |
* @return A string array sorted alphabetically with each string being an anagram pair, separated | |
* by a single space and ordered alphabetically. For example, if the pair "was" and "saw" is found", | |
* the outputted line is "saw was". | |
*/ | |
private static String[] findAnagrams(String... input) { | |
// Key is ordered string, value is a list of all strings that have the characters of the key | |
HashMap<String, LinkedList<String>> parsedWords = new HashMap<>(); | |
ArrayList<String> output = new ArrayList<>(); | |
for (String s : input) { | |
char[] chars = s.toCharArray(); | |
Arrays.sort(chars); | |
String ordered = new String(chars); | |
if (parsedWords.containsKey(ordered)) { | |
LinkedList<String> list = parsedWords.get(ordered); | |
for (String listString : list) { | |
if (s.compareTo(listString) > 0) { | |
output.add(listString + " " + s); | |
} else { | |
output.add(s + " " + listString); | |
} | |
} | |
list.add(s); | |
} else { | |
LinkedList<String> newList = new LinkedList<>(); | |
newList.add(s); | |
parsedWords.put(ordered, newList); | |
} | |
} | |
Collections.sort(output); | |
return output.toArray(new String[0]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment