Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
Solution:O(n)
public class Solution { public ArrayList<String> anagrams(String[] strs) { ArrayList<String> list = new ArrayList<String>(); if(strs == null || strs.length == 0) return list; HashMap<String,String> map = new HashMap<>(); for(String s:strs){ char[] set = s.toCharArray(); Arrays.sort(set); String key = new String(set); if(map.get(key)==null){ map.put(key,s); }else{ if(!list.contains(map.get(key))) list.add(map.get(key)); list.add(s); } } return list; } }
沒有留言:
張貼留言