171.Anagrams

1.Description(Medium)

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

Notice

All inputs will be in lower-case

Example

Given["lint", "intl", "inlt", "code"], return["lint", "inlt", "intl"].

Given["ab", "ba", "cd", "dc", "e"], return["ab", "ba", "cd", "dc"].

Challenge

What is Anagram?

  • Two strings are anagram if they can be the same after change the order of characters.

2.Code

用一个HashMap<String,List<String>>来记录,取出每个string排序然后把与原顺序的string记录进hashmap的list中,最后判断ma。p.values()里面的每个list的size如果>1,就说明有他的anagrams,直接addAll进去就行了。

public List<String> anagrams(String[] strs) {
        List<String> result=new ArrayList<String>();
        if(strs==null || strs.length==0){
            return result;
        }

        HashMap<String,List<String>> map=new HashMap<>();
        for(int i=0;i<strs.length;i++){
            //fetch this word and make it array then sort it then remake a string
            char[] current=strs[i].toCharArray();
            Arrays.sort(current);
            String key=new String(current);

            if(map.containsKey(key)){
                map.get(key).add(strs[i]);
            }else{
                List<String> word=new ArrayList<String>();
                word.add(strs[i]);
                map.put(key, word);
            }       
        }


        for(List<String> element:map.values()){
            if(element.size()>1){
                result.addAll(element);
            }
        }
        return result;
    }

Last updated