Anagrams
Anagrams
问题:
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
思路:
Anagrams:排序后的String作为Key值
public class Solution { public List<String> anagrams(String[] strs) { List<String> list = new ArrayList<String>(); if(strs == null || strs.length == 0) return list; HashMap<String, List<String>> hashMap = new HashMap<String,List<String>>(); for(int i = 0; i < strs.length; i++) { String val = strs[i]; char[] array = val.toCharArray(); Arrays.sort(array); String key = new String(array); if(hashMap.containsKey(key)) { hashMap.get(key).add(val); } else { List<String> tmp = new ArrayList(); tmp.add(val); hashMap.put(key, tmp); } } for(String key: hashMap.keySet()) { List<String> tmp = hashMap.get(key); if(tmp.size() > 1) { list.addAll(tmp); } } return list; } }
posted on 2015-03-15 16:10 zhouzhou0615 阅读(142) 评论(0) 编辑 收藏 举报