标签:
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
解题思路:首先要理解,什么是anagrams,ie。“tea”、“tae”、“aet”,然后就十分好做了,new一个hashmap,使用一个排过序的String作为key,重复了就往里面添加元素,这里出现一个小插曲,就是排序的时候不要用PriorityQueue,因为PriorityQueue是采用堆排序的,仅保证堆顶元素为优先级最高的(害了我好久)JAVA实现如下:
static public List<String> anagrams(String[] strs) { List<String> list = new ArrayList<String>(); HashMap<String, List<String>> hm = new HashMap<String, List<String>>(); for (int i = 0; i < strs.length; i++) { char [] c=strs[i].toCharArray(); Arrays.sort(c); String sortString=new String(c); if (!hm.containsKey(sortString)) hm.put(sortString.toString(), new ArrayList<String>()); hm.get(sortString.toString()).add(strs[i]); } Iterator<String> iterator = hm.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); if (hm.get(key).size() > 1) list.addAll(hm.get(key)); } return list; }
Java for LeetCode 049 Anagrams
标签:
原文地址:http://www.cnblogs.com/tonyluis/p/4504804.html