标签:java leetcode array string hashmap
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
题目中是找出所有的字符串由相同的字符组成,只是顺序不同。public List<String> anagrams(String[] strs) { List<String> list = new ArrayList<String>(); if (strs == null || strs.length == 0) { return list; } int len = strs.length; HashMap<String, ArrayList<String>> hashMap = new HashMap<String, ArrayList<String>>(); for (int i = 0; i< len; i++) { char[] ch = strs[i].toCharArray(); Arrays.sort(ch); String str = new String(ch); if (hashMap.containsKey(str)) { hashMap.get(str).add(strs[i]); } else { ArrayList<String> arr = new ArrayList<String>(); arr.add(strs[i]); hashMap.put(str, arr); } } Iterator<ArrayList<String>> ite = hashMap.values().iterator(); while(ite.hasNext()) { ArrayList<String> item = ite.next(); if(item.size()>1) list.addAll(item); } return list; }
标签:java leetcode array string hashmap
原文地址:http://blog.csdn.net/u010378705/article/details/30101635