Untitled
unknown
plain_text
a month ago
1.9 kB
2
Indexable
Never
public class Solution { // DO NOT MODIFY THE LIST. IT IS READ ONLY public ArrayList<ArrayList<Integer>> anagrams(final List<String> A) { ArrayList<Pair> newList = new ArrayList<Pair>(); for(int i = 1; i <= A.size(); i++) { newList.add(new Pair(i, lexicographycalString(A.get(i-1)))); } HashMap<String, ArrayList<Integer>> hashMaps = new HashMap<String, ArrayList<Integer>>(); for(int i = 1; i <= newList.size(); i++) { Pair cur = newList.get(i-1); if(!hashMaps.containsKey(cur.value)) { hashMaps.put(cur.value, createArrayListWithDefault(cur.index)); continue; } ArrayList<Integer> existingList = hashMaps.get(cur.value); existingList.add(cur.index); } ArrayList<ArrayList<Integer>> newArrayList = new ArrayList<ArrayList<Integer>>(); for(ArrayList<Integer> results : hashMaps.values()) { newArrayList.add(results); } return newArrayList; } public String lexicographycalString(String value){ char [] newArray = value.toCharArray(); Arrays.sort(newArray); return String.copyValueOf(newArray); } public ArrayList<Integer> createArrayListWithDefault(int value){ ArrayList<Integer> newArrayList = new ArrayList<Integer>(); newArrayList.add(value); return newArrayList; } class Pair implements Comparable<Pair> { int index; String value; public Pair(int index, String value){ this.index = index; this.value = value; } @Override public int compareTo(Pair o) { return this.value.compareTo(o.value); } } }
Leave a Comment