Given an array of strings, return all groups of strings that are anagrams.
Given ["lint", "intl", "inlt", "code"]
, return["lint", "inlt", "intl"]
.
Given ["ab", "ba", "cd", "dc", "e"]
, return["ab", "ba", "cd", "dc"]
.
public class Solution { /** * @param strs: A list of strings * @return: A list of strings */ public List<String> anagrams(String[] strs) { // write your code here List<String> result = new ArrayList<String>(); if(strs == null || strs.length == 0) return result; HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>(); for(int i = 0; i < strs.length; i++){ String temp = getCount(strs[i]); if(!map.containsKey(temp)) map.put(temp, new ArrayList<String>()); map.get(temp).add(strs[i]); } for(ArrayList<String> value: map.values()){ if(value.size() > 1) result.addAll(value); } return result; } public String getCount(String str){ StringBuilder result = new StringBuilder(); int[] count = new int[26]; for(int i = 0; i < str.length(); i++){ count[str.charAt(i) - 'a']++; } for(int i = 0; i < 26; i++) result.append(count[i]); return result.toString(); } }