LintCode: 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"]

What is Anagram?

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

解题方法

  1. using char[26] to sort 26 letters.

  2. use HashMap to store the same strings.

    Runtime complexity:n * O(L)

    Space complexity: O(L)

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

        Map<String, List<String>> map = new HashMap<>();
        for(int i = 0; i < strs.length; i++){
            char[] chars = new char[26];
            for(int j = 0; j < strs[i].length(); j++){
                chars[ strs[i].charAt(j) - 'a' ] += 1;
            }
            String strSort = Arrays.toString(chars);  //*********************************as key
            if(map.containsKey(strSort)){
                List<String> list = map.get(strSort);
                list.add(strs[i]);
                map.put(strSort, list);
            }else{
                List<String> lists = new ArrayList<>();
                lists.add(strs[i]);
                map.put(strSort, lists);
            }
        }

        List<String> res = new ArrayList<>();
        for(Map.Entry<String, List<String>> entry : map.entrySet()){
            if(entry.getValue().size() >= 2){
                res.addAll(entry.getValue());
            }
        }
        return res;
    }

results matching ""

    No results matching ""