yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #49 Group Anagrams #107

Open yokostan opened 6 years ago

yokostan commented 6 years ago

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] Note:

All inputs will be in lowercase. The order of your output does not matter.

Solutions: class Solution { public List<List> groupAnagrams(String[] strs) { List<List> res = new ArrayList<>(); HashMap<String, List> map = new HashMap<>();

for (int i = 0; i < strs.length; i++) {
    char[] ch = strs[i].toCharArray();
    Arrays.sort(ch);
    if (map.containsKey(String.valueOf(ch))) {
        map.get(String.valueOf(ch)).add(strs[i]);
    } else {
        List<String> each = new ArrayList<>();
        each.add(strs[i]);
        map.put(String.valueOf(ch), each);
    }
}
for (List<String> item: map.values()) {
    res.add(item);
}
return res;

} }

Points:

  1. HashMap is an amazing data type to count for data, with a key and a matching value. HashMap.containsKey(key) will return true if a key has already existed in the mapping. HashMap.get(key) will get the matching value for a certain key. HashMap.put(key, value) will add in the value and key to the mapping.