力扣49. 字母异位词分组

打印 上一主题 下一主题

主题 1031|帖子 1031|积分 3093

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意次序返回结果列表。
    字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
  
示例 1:
  1. <strong>输入:</strong> strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
  2. <strong>输出: </strong>[["bat"],["nat","tan"],["ate","eat","tea"]]
复制代码
示例 2:
  1. <strong>输入:</strong> strs = [""]
  2. <strong>输出: </strong>[[""]]
复制代码
示例 3:
  1. <strong>输入:</strong> strs = ["a"]
  2. <strong>输出: </strong>[["a"]]
复制代码

提示:


  • 1 <= strs.length <= 104
  • 0 <= strs.length <= 100
  • strs 仅包含小写字母

代码:
  1. class Solution {
  2. public:
  3.     vector<vector<string>> groupAnagrams(vector<string>& strs) {
  4.         map<string, vector<string>> hash;
  5.         for(int i = 0; i < strs.size(); i++){
  6.             string key = strs[i];
  7.             sort(key.begin(), key.end());
  8.             hash[key].push_back(strs[i]);
  9.         }
  10.         vector<vector<string>> res;
  11.         for(map<string, vector<string>>::iterator temp = hash.begin(); temp != hash.end(); temp++){
  12.             res.push_back(temp->second);
  13.         }
  14.         
  15.         return res;
  16.     }
  17. };
复制代码

   解题思绪:
  (1)使用哈希头脑
  (2)因为单词所用的字母雷同,我们可以将某个单词进行排序后,作为哈希表的 key

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

惊雷无声

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表