思路:基本思路是这样的,建立一个string - > list<string> 的hash表, key是字符串的字符按序排列的字符串,然后遍历list的size即可
代码:
public List<String> anagrams(String[] strs) { List<String> rs = new LinkedList<String>(); Map<String, List<String>> results = new HashMap<String, List<String>>();//字母序列(统一顺序排序) - 单词的映射 for(String s : strs){ StringBuffer ss = new StringBuffer(s); sort(ss); String sb = ss.toString(); if(results.get(sb) != null){ results.get(sb).add(s); }else { List<String> list = new LinkedList<String>(); list.add(s); results.put(sb, list); } } for(Map.Entry<String, List<String>> en : results.entrySet()){ List<String> list = en.getValue(); if(list.size() > 1){ for(String s : list){ rs.add(s); } } } return rs; } public void sort(StringBuffer ss){ for(int i = 0; i< ss.length(); ++i){ for(int j = i +1; j< ss.length(); ++j){ if(ss.charAt(j) > ss.charAt(i)){ char t = ss.charAt(j); ss.setCharAt(j, ss.charAt(i)); ss.setCharAt(i, t); } } } }
原文地址:http://blog.csdn.net/youmengjiuzhuiba/article/details/45768679