标签:
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; } }
标签:
原文地址:http://www.cnblogs.com/incrediblechangshuo/p/5836129.html