简体   繁体   中英

Java group anagrams without sorting array

I see the below solution to a popular question to group anagrams. I want to achieve it without sorting. I ran through the solution in my IDE to debug and understand step by step but I just can't seem to figure out what we are doing in the lines I have mentioned below on what we are doing in the algorithm. The IDE just shows a bunch of commas.

What can I try next?

    public List<List<String>> groupAnagrams(String[] strs) {
    List<List<String>> result = new ArrayList<List<String>>();
 
    HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
    for(String str: strs){
        char[] arr = new char[26];
        for(int i=0; i<str.length(); i++){
            arr[str.charAt(i)-'a']++; -- what are we doing here?
        }
        String ns = new String(arr); -- what does ns actually have?
 
        if(map.containsKey(ns)){
            map.get(ns).add(str);
        }else{
            ArrayList<String> al = new ArrayList<String>();
            al.add(str);
            map.put(ns, al);
        }
    }
 
    result.addAll(map.values());
 
    return result;
}
arr[str.charAt(i)-'a']++; -- what are we doing here? 

Just mapping char 'a' to 'z' to index 0 to 26 in arr and incrementing its count. So a string like 'aaab' will translate to 'arr[0] = 3 and arr[1]=1'

String ns = new String(arr); -- what does ns actually have?

Converting arr of char to string. words which are anagram will have same values of count in arr and will result in same string ns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM