LeetCode Daily Question 2
Mar 6th 2022
3 月 6 日 每日一题
题目:49. Group Anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
eg: Input: Input: strs = [“eat”,”tea”,”tan”,”ate”,”nat”,”bat”]
Output: [[“bat”],[“nat”,”tan”],[“ate”,”eat”,”tea”]]
思路
使用 count sort,以避免对每一个 str 进行 sort。首先建立一个对于 26 个字母的 count[26],记录每个字母出现的次数,并且返回一个形式为 a2b2(abab)的 key。使用一个 unorder map 储存 <key,vector
时间复杂度为 O(mn) 空间复杂度为 O(26m),m 为 str 数目,n 为单个 str 长度。
代码
1 | vector<vector<string>> groupAnagrams(vector<string>& strs) { |