import java.util.*;

/**
 * NC294 字母异位词分组
 * @author d3y1
 */
public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param strs string字符串一维数组 
     * @return string字符串二维数组
     */
    public String[][] groupAnagrams (String[] strs) {
        // keyWord -> words
        HashMap<String, ArrayList<String>> map = new HashMap<>();

        char[] keyWordChars;
        String keyWord;
        ArrayList<String> wordList;
        for(String word: strs){
            keyWordChars = word.toCharArray();
            Arrays.sort(keyWordChars);
            keyWord = String.valueOf(keyWordChars);
            
            wordList = map.get(keyWord);
            if(wordList != null){
                wordList.add(word);
            }else{
                wordList = new ArrayList<>();
                wordList.add(word);
            }
            map.put(keyWord, wordList);
        }

        String[][] resultArr = new String[map.size()][];
        int i = 0;
        int j = 0;
        for(String key: map.keySet()){
            wordList = map.get(key);
            resultArr[i] = new String[wordList.size()];
            for(String word: wordList){
                resultArr[i][j++] = word;
            }
            i++;
            j = 0;
        }

        return resultArr;
    }
}