leetcode-49. 字母異位詞分組

題目

給定一個字符串數組,將字母異位詞組合在一起。字母異位詞指字母相同,但排列不同的字符串。

示例

輸入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
輸出:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]

在這裏插入圖片描述

class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {
            List<List<String>>list=new ArrayList<>();
            Map<String,Integer> map=new HashMap<>();
            //整體思路就是,將每一個字符串轉化爲數組形式
            //sort一下每一個數組,最後得到一個遞減的字符串(也就是bca和cab最終都將變成abc)
            //判斷map中是否存在該字符
            //如果沒有,新建一個list_copy,將當前沒有排序過的字符串插入list_copy
            //最後將list_copy插入list。此時同時將字符串存入map
            //map的key爲當前排序過後的字符串,value爲list_copy在list中的位置
            for(String str:strs){
                char[]temps=str.toCharArray();
                Arrays.sort(temps);
                String temp=String.valueOf(temps);
                Integer index=map.get(temp);
                if(index!=null){
                    list.get(index).add(str);
                }else{
                    List<String>list_copy=new ArrayList<>();
                    list_copy.add(str);
                    list.add(new ArrayList(list_copy));
                    map.put(temp,list.size()-1);
                }
            }
            return list;
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章