码迷,mamicode.com
首页 > 其他好文 > 详细

Anagrams

时间:2016-07-16 06:42:09      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

Given an array of strings, return all groups of strings that are anagrams.

 Notice

All inputs will be in lower-case

Example

Given ["lint", "intl", "inlt", "code"], return ["lint", "inlt", "intl"].

Given ["ab", "ba", "cd", "dc", "e"], return ["ab", "ba", "cd", "dc"].

Analysis:

If there is only one group of anagrams, it is very easy. However, as we need to find all groups of anagrams, it is not easy to do it. The idea is we first sort all the strings, and add it to hashmap. If the string exists in the hashmap, we will add the string to the value (which is a list) of the key.

 1 public class Solution {
 2     /**
 3      * @param strs: A list of strings
 4      * @return: A list of strings
 5      */
 6     public List<String> anagrams(String[] strs) {
 7         HashMap<String, ArrayList<String>> record = new HashMap<String, ArrayList<String>>();
 8         List<String> res = new ArrayList<String>();
 9         
10         for(String s : strs){
11             char[] arr = s.toCharArray();
12             Arrays.sort(arr);
13             String newWord = new String(arr);
14             if(!record.containsKey(newWord)){
15                 record.put(newWord, new ArrayList<String>());
16             }
17              record.get(newWord).add(s);
18         }
19         
20         for(String s : record.keySet()){
21             if(record.get(s).size() > 1){
22                 res.addAll(record.get(s));
23             }
24         }
25         return res;
26     }
27 }

 

 

Anagrams

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5675107.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!