LeetCode --- 49. 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.

思路:

        如果直接说有蛮力的话,个人觉得估计是会超时的,所以也没尝试蛮力的操作。这里直接尝试的hashmap的方式,也即迭代整个String[],将每一个String排序之后,比对hash表,如果表中有该键值了,那么将这一个String元素插入到hash表中的链表中,否则建立一个新的链表然后将该元素插入并将链表put进hash表

代码:

class Solution {
    public List> groupAnagrams(String[] strs) {
        HashMap> hashMap = new HashMap<>();
        List> result = new ArrayList<>();
        for(int i = 0;i < strs.length;i++){
            char[] temp = strs[i].toCharArray();
            Arrays.sort(temp);
            String ts = String.copyValueOf(temp);
            if(hashMap.containsKey(ts)){
                hashMap.get(ts).add(strs[i]);
            }else{
                List list = new ArrayList<>();
                list.add(strs[i]);
                hashMap.put(ts,list);
            }
        }
        Iterator it = hashMap.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry m = (Map.Entry) it.next();
            result.add((List) m.getValue());
        }
        return result;
    }
}

你可能感兴趣的:(LeetCode记录)