Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
把给的string都变成charArray然后排序, 把sort好的再变成string 存入hashmap, map 的value值为一个list<> list内存放变形之前的string.
如果一个string在hashmap中出现过 这个string一定是个变形词 把各个string放入对应的list中,遍历一次时间复杂度O(nlogn) + O(n*klogk) = O(nlogn)
public class Solution { public List<List<String>> groupAnagrams(String[] strs) { List<List<String>> res = new ArrayList<List<String>>(); if (strs == null || strs.length == 0) { return res; } Arrays.sort(strs); HashMap<String, List<String>> map = new HashMap<String, List<String>>(); for (String s : strs) { char[] chararray = s.toCharArray(); Arrays.sort(chararray); String temstr = new String(chararray); if (map.containsKey(temstr)) { map.get(temstr).add(s); } else { List<String> tem = new ArrayList<String>(); tem.add(s); map.put(temstr, tem); } } for (List<String> l : map.values()) { res.add(l); } return res; } }
没有评论:
发表评论