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.
题目地址:leetcode Group Anagrams
题目大意: 给定一些字符串,有的字符串是由字符串颠倒的,比如eat->tea 要求找出所有的这些单词
思路:直接用将每个字符串放入排好序后的桶中(hash)即可。
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Solution {public : vector<vector<string>> groupAnagrams (vector<string>& strs) { unordered_map<string, vector<string>> map; for (string &s : strs){ string t (s) ; sort (t.begin (), t.end ()); map[t].push_back (s); } vector<vector<string>> ans; auto it = map.begin (); for (;it != map.end ();++it){ ans.push_back (it->second); } return ans; } };
Python
1 2 3 4 5 6 7 8 9 10 class Solution (object ): def groupAnagrams (self, strs ): """ :type strs: List[str] :rtype: List[List[str]] """ m = collections.defaultdict(list ) for s in strs: m['' .join(sorted (s))].append(s) return list (m.values())
本文是leetcode如下的题解
更多题解可以查看: https://www.hrwhisper.me/leetcode-algorithm-solution/