[LeetCode] 49. Group Anagrams 分组变位词

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
Return:

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
] 

Note: All inputs will be in lower-case.

给一个含字符串的数组,字符串是变位词的分在一组,返回所有分组。变位词就是一个单词通过改变单词当中的字母顺序变成另外一个单词。

解法:迭代数组中的每一个单词,把单词的字符进行排列,以排序后的单词为key原单词为value,添加到HashMap中,如果是变位词的话,排序后应该是一样的单词,所以会添加到同一个key里面。然后在按key的分组把value添加到list,返回list。

Java:

public List<List<String>> groupAnagrams(String[] strs){  
    List<List<String>> lists=new ArrayList<List<String>>();  
    Map<String,List<String>> map=new HashMap<String,List<String>>();  
    for(String str:strs){  
        char[] chs=str.toCharArray();  
        Arrays.sort(chs);  
        String tmp=new String(chs);  
        if(map.containsKey(tmp))  
            map.get(tmp).add(str);  
        else{  
            List<String> list=new ArrayList<String>();  
            list.add(str);  
            map.put(tmp, list);  
        }  
    }  
    for(String str:map.keySet()){  
        lists.add(map.get(str));  
    }  
    return lists;  
}

Java:

public class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for (String s : strs) {
            char[] sc = s.toCharArray();
            Arrays.sort(sc);
            String key = String.valueOf(sc);
            map.putIfAbsent(key, new ArrayList<>());
            map.get(key).add(s);
        }
        return new ArrayList<>(map.values());
    }
}

Python:HashMap

class Solution(object):
    def groupAnagrams(self, strs):
        anagrams_map, result = collections.defaultdict(list), []

        for s in strs:
            sorted_str = ("").join(sorted(s))
            anagrams_map[sorted_str].append(s)

        for anagram in anagrams_map.values():
            anagram.sort()
            result.append(anagram)
        return result

C++:

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> res;
        unordered_map<string, vector<string>> m;
        for (string str : strs) {
            string t = str;
            sort(t.begin(), t.end());
            m[t].push_back(str);
        }
        for (auto a : m) {
            res.push_back(a.second);
        }
        return res;
    }
};

C++:Array

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> res;
        unordered_map<string, vector<string>> m;
        for (string str : strs) {
            vector<int> cnt(26, 0);
            string t = "";
            for (char c : str) ++cnt[c - 'a'];
            for (int d : cnt) t += to_string(d) + "/";
            m[t].push_back(str);
        }
        for (auto a : m) {
            res.push_back(a.second);
        }
        return res;
    }
};

 

类似题目:

[LeetCode] 249. Group Shifted Strings 分组偏移字符串

 

All LeetCode Questions List 题目汇总

 

posted @ 2018-03-10 09:17  轻风舞动  阅读(479)  评论(0编辑  收藏  举报