49. Group Anagrams

来源:互联网 发布:淘宝网开店要交钱吗 编辑:程序博客网 时间:2024/05/01 22:35

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:

  1. For the return value, each inner list's elements must follow the lexicographic order.
  2. All inputs will be in lower-case.

Subscribe to see which companies asked this question

以string为源生成key 相同字母不同排序的key相同 再以hashmap存就好

public class Solution {    public List<List<String>> groupAnagrams(String[] strs) {        List<List<String>> ret = new ArrayList<>();        if(strs==null||strs.length == 0)return ret;        HashMap<String,List<String>>hmap = new HashMap<>();        for(int i = 0;i<strs.length;i++){            char [] chars = strs[i].toCharArray();            Arrays.sort(chars);            String temp = new String(chars);            if(!hmap.containsKey(temp)){                List<String> retList = new ArrayList<>();                retList.add(strs[i]);                hmap.put(temp,retList);            }else{                hmap.get(temp).add(strs[i]);            }        }                Iterator<Map.Entry<String,List<String>>>iterator = hmap.entrySet().iterator();          while(iterator.hasNext()) {             Map.Entry<String,List<String>> entry = iterator.next();             List<String> temp_list = entry.getValue();             Collections.sort(temp_list);             ret.add(temp_list);          }                 return ret;    }}

0 0
原创粉丝点击