import java.util.*;


public class Solution {
    
    public class ComparaString implements Comparator<String> {
        @Override
        public int compare (String str1, String str2) {
            
            str1 = process(str1);
            str2 = process(str2);
            
            int len1 = str1.length();
            int len2 = str2.length();
            int p1 = 0;
            int p2 = 0;
            while (p1 < len1 && p2 < len2) {
                if (str1.charAt(p1) < str2.charAt(p2)) {
                    return -1;
                }
                else if (str1.charAt(p1) > str2.charAt(p2)) {
                    return 1;
                }
                else {
                    p1++;
                    p2++;
                }
            }
            if (len1 < len2) {
                return -1;
            }
            else if (len1 > len2) {
                return 1;
            }
            else {
                return 0;
            }
        }
    }
    
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param strs string字符串一维数组 
     * @return string字符串二维数组
     */
    public String[][] groupAnagrams (String[] strs) {
        // write code here

        if (1 == strs.length) {
            String[][] res = new String[][]{{strs[0]}};
        }
        
        HashMap<String, String> hashMap = new HashMap<>();
        ArrayList<String> copyStrs = new ArrayList<>();
        for (String str : strs) {
            copyStrs.add(str);
            hashMap.put(str, process(str));
        }
        copyStrs.sort(new ComparaString());
        
        ArrayList<ArrayList<String>> arr = new ArrayList<>();
        ArrayList<String> tmpArr = new ArrayList<>();
        for (String str : copyStrs) {
            if (tmpArr.size() == 0) {
                tmpArr.add(str);
            }
            else {
                if (hashMap.get(tmpArr.get(0)).equals(hashMap.get(str))) {
                    tmpArr.add(str);
                }
                else {
                    arr.add(tmpArr);
                    tmpArr = new ArrayList<>();
                    tmpArr.add(str);
                }
            }
        }
        if (tmpArr.size() != 0) {
            arr.add(tmpArr);
        }
        String[][] res = new String[arr.size()][];
        for (int i = 0; i < arr.size(); i++) {
            res[i] = new String[arr.get(i).size()];
            for (int j = 0; j < arr.get(i).size(); j++) {
                res[i][j] = arr.get(i).get(j);
            }
        }
        return res;
    }
    
    public String process(String str) {
        char[] chrs = str.toCharArray();
        Arrays.sort(chrs);
        StringBuffer sb = new StringBuffer("");
        for (char chr : chrs) {
            sb.append(chr);
        }
        return new String(sb);
    }
}