首页 > 代码库 > LeetCode-Group Anagrams

LeetCode-Group Anagrams

Given an array of strings, group anagrams together.For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return:[  ["ate", "eat","tea"],  ["nat","tan"],  ["bat"]]Note: All inputs will be in lower-case.
public class Solution {    public List<List<String>> groupAnagrams(String[] strs) {        if(strs==null || strs.length==0){            return null;        }        List<List<String>> resList=new ArrayList<List<String>>();        Map<String, List<String>> map=new HashMap<String, List<String>>();        for(int i=0; i<strs.length; i++){            String str=strs[i];            char[] chars=str.toCharArray();            Arrays.sort(chars);            String key=new String(chars);            if(map.containsKey(key)){                List<String> strList=map.get(key);                strList.add(str);                map.put(key,strList);            }            else{                List<String> strList=new ArrayList<String>();                strList.add(str);                map.put(key, strList);            }        }        for(String key : map.keySet()){            resList.add(map.get(key));        }        return resList;    }}

 

LeetCode-Group Anagrams