LeetCode: 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:
For the return value, each inner list's elements must follow the lexicographic order.
All inputs will be in lower-case.
Find the sequence of words in the given string array that can form different alphabetic orders. For details, refer to the example.
Solution: strings that match the meaning of the question can be sorted by letters in the same order. Therefore, we only need to use HashMap to store the corresponding sequence and the matching string.
Code:
public class Solution { public List
anagrams(String[] strs) { Map
pairs = new HashMap
(); List
result = new LinkedList
(); Map
remain = new HashMap
(); for (String s:strs) { char[] key = s.toCharArray(); Arrays.sort(key); if (key.length == 0) key = null; String k = key != null ? new String(key) : null; String pair = pairs.put(k, s); if (pair != null) { result.add(pair); remain.put(k, s); } } result.addAll(remain.values()); return result; }}