Java Anagram Search Algorithm

I have an array of Strings in Java. I need to find anagrams from an array and print them on the screen.

I'm having difficulty with the part where I have to compare the elements of the array to check if they are anagrams or not. How should I do it? I would have to do a loop to go through the array, obviously.

I think I could sort String and then compare them (because if they are anagrams they will contain the same letters in the same order when sorting), but how would I disable them to get the original word

+4
source share
2 answers

If you are in alphabetical order of letters than a hash, they should be the same ...

 Map<String, List<String>> words = new HashMap<String, List<String>>(); for(String word : incomingWords) { final String key = alphabetize(word); if(words.contains(key)){ words.get(key).add(word); } else { words.put(key, new ArrayList<String>()); words.get(key).add(word); } } 

Now you have a Map words that are anagrams ... You will also have a List in Map that has only 1 entry, you can remove them from the map to just save Map which have other anagrams from your dictionary ...

+4
source

You can use a Map , which maps an ordered String to a Collection the array indexes, which are anagrams of an ordered String .

0
source

Source: https://habr.com/ru/post/1396954/


All Articles