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.
題意:找出給定字符串數組中,能組成不同字母順序的單詞的序列,具體看例子
解決思路:符合題意的字符串只要對字母排序,就會呈現一樣的順序,所以我們只要用HashMap存儲對應的序列和符合要求的字符串就可以
代碼:
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;
}
}