Anagrams

来源:互联网 发布:单片机应用技术 编辑:程序博客网 时间:2024/05/01 06:31

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

Analysis: Using a hash table groups all anagrams together. We can sort each string first and using such sorted string as the key to store it in the hash table. 

public class Solution {    public ArrayList<String> anagrams(String[] strs) {        ArrayList<String> res = new ArrayList<String>();        HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();                for(int i=0; i<strs.length; i++) {            char[] charArray = strs[i].toCharArray();            Arrays.sort(charArray);            String sortedString = new String(charArray);            if(!map.containsKey(sortedString)) map.put(sortedString, new ArrayList<String>());            map.get(sortedString).add(strs[i]);        }                for(String s : map.keySet()) {            if(map.get(s).size()>1) res.addAll(map.get(s));     // return groups only        }        return res;    }}



0 0