Group Anagrams

Run Settings
LanguageJava
Language Version
Run Command
import java.util.Arrays; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.stream.Collectors; class Main { public static void main(String[] args) { /** * Given an array of strings strs, group the anagrams together. * * Input: strs = ["eat","tea","tan","ate","nat","bat"] * Output: [["bat"],["nat","tan"],["ate","eat","tea"]] */ String[] strs = {"eat","tea","tan","ate","nat","bat"}; // Map to collect the sorted string as key and the ocurrences in the list as value Map<String, List<String>> occurrencesGroups = new TreeMap<>(); // Iterating the original strings to check one by one for (String str : strs) { // Sorting string to prepare it for searching String sortedStr = sortString(str); // Value reference to add occurrences List<String> occurrences = null; // If the string has occurrences, then get the List of occurrences // Otherwise, put the string as key and add a new list to add new // occurrences if (occurrencesGroups.containsKey(sortedStr)) { occurrences = occurrencesGroups.get(sortedStr); } else { occurrences = new ArrayList<String>(); occurrencesGroups.put(sortedStr, occurrences); } // Adding occurrence to the reference list occurrences.add(str); } // Collecting values to match expected output format List<List<String>> occurrencesList = new ArrayList<>(occurrencesGroups.values()); System.out.println(occurrencesList); } private static String sortString(String str) { return Arrays.stream(str.split("")) .sorted() .collect(Collectors.joining()); } }
Editor Settings
Theme
Key bindings
Full width
Lines