Given an array of strings, group anagrams together.
For example, given:
Return:
["eat", "tea", "tan", "ate", "nat", "bat"]
,Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
public class Solution { public List> groupAnagrams(String[] strs) { List
> ret = new ArrayList
>(); int len = strs.length; if(0 == len) return ret; Map
> sMap = new HashMap >(); //for(String s : strs){ for(int i = 0; i < len; ++i){ String s = strs[i]; char[] sArr = s.toCharArray(); Arrays.sort(sArr); String sSorted = new String(sArr); if(!sMap.containsKey(sSorted)){ sMap.put(sSorted, new ArrayList ()); } sMap.get(sSorted).add(i); } for(String key : sMap.keySet()){ List rEle = new ArrayList (); List iList = sMap.get(key); for(Integer i : iList){ rEle.add(strs[i]); } Collections.sort(rEle); ret.add(rEle); } return ret; } }
No comments:
Post a Comment