Anagrams
Given an array of strings, return all groups of strings that are anagrams.
Example
Given ["lint", "intl", "inlt", "code"]
, return ["lint", "inlt", "intl"]
.
Given ["ab", "ba", "cd", "dc", "e"]
, return ["ab", "ba", "cd", "dc"]
.
Note
All inputs will be in lower-case
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> list=new ArrayList<String>(); if(strs==null ||strs.length==0) return list; HashMap<String,Integer> visited=new HashMap<String,Integer>(); for(int i=0;i<strs.length;i++) { char[] ch=strs[i].toCharArray(); Arrays.sort(ch); String s=new String(ch); if(visited.containsKey(s)) { int index=visited.get(s); if(index!=-1) { list.add(strs[index]); visited.put(s,-1); } list.add(strs[i]); } else { visited.put(s,i); } } return list; } }