0
点赞
收藏
分享

微信扫一扫

2024年端午节放假通知

微笑沉默 2024-06-05 阅读 6

思路 : 字母异位词是字母排序不同,但字母总量相同的字符串,可以用一个排序后的String充当key,一个List收集对应该String的全部异位词。

主要API用法:

toCharArray : String转char类型数组

map.values() 取出Map的全部value值作为一个列表。

如果有疑问和更好的见解欢迎交流

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        //toCharArray
        //Arrays.sort()
        List<List<String>> res = new ArrayList<>();
        Map<String,List<String>> m = new HashMap<>();
        for(int i = 0;i<strs.length;++i){
            char[] cArray = strs[i].toCharArray();
            Arrays.sort(cArray);
            String tempString = new String(cArray);
            if(m.containsKey(tempString)){
                List<String> temp = m.get(tempString);
                temp.add(strs[i]);
                m.put(tempString,temp);
            }
            else{
                List<String> temp = new ArrayList<String>();
                temp.add(strs[i]);
                m.put(tempString, temp);
            }
        }
        return new ArrayList<List<String>>(m.values());
    }
}
举报

相关推荐

0 条评论