字母异位词分组 (Group Anagrams)

 

思路:

// @Title: 字母异位词分组 (Group Anagrams)
// @Author: qisiii
// @Date: 2024-05-10 23:20:15
// @Runtime: 7 ms
// @Memory: 46.6 MB
// @comment: 
// @flag: 
class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String,List<String>> hash=new HashMap<>();
        for(String str:strs){
            String order=ordered(str);
            List<String> list=hash.getOrDefault(order,new ArrayList<>());
            list.add(str);hash.put(order,list);

        }
        List<List<String>> result=new ArrayList<>();
        for(String key:hash.keySet()){
            result.add(hash.get(key));
        }
        return result;
    }

    private String ordered(String str){
        char[] temp=str.toCharArray();
        Arrays.sort(temp);
        return new String(temp);
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18