您的位置:首页 > 其它

Leetcode 49: Group Anagrams

2015-12-17 07:05 369 查看
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.
Solution:

First sort the string array to keep lexicographic order. Then for each string, convert it to a string with characters in lexicographic
order. If the converted string is the same, the two strings are anagram. Use a hash map to add each original string to anagram group and finally return the values of the map.

Time complexity: if the array length is n, the average length of strings is m, time complexity is O(n*mlogm)

Space complexity: O(n)?

public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Arrays.sort(strs);
HashMap<String, List<String>> map = new HashMap<String, List<String>>();

for (int i = 0; i < strs.length; i++) {
String current = strs[i];
char[] chararray = current.toCharArray();
Arrays.sort(chararray);
String keystr = new String(chararray);
List<String> group = map.getOrDefault(keystr, new ArrayList<String>());
group.add(current);
map.put(keystr, group);
}

return new ArrayList<List<String>> (map.values());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  String Hash Table