leetcode49-Group Anagrams(同构词(相同字母组成的单词)分类)
2016-04-09 17:59
501 查看
问题描述:
Given an array of strings, group anagrams together.
For example, given:
Return:
Note:
For the return value, each inner list’s elements must follow the lexicographic order.
All inputs will be in lower-case.
给出一个字符串数组S,按照同构词(相同字母组成的单词)分类,每类单词按照字典排序。
问题求解:
利用hash表。
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:
For the return value, each inner list’s elements must follow the lexicographic order.
All inputs will be in lower-case.
给出一个字符串数组S,按照同构词(相同字母组成的单词)分类,每类单词按照字典排序。
问题求解:
利用hash表。
class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { int n=strs.size(); if(n==0) return vector<vector<string>> (); vector<vector<string>> res; unordered_map<string, vector<string>> hash; //(1)将字符串数组先按字典顺序排序 sort(strs.begin(), strs.end()); //(2)构造hash表 for(int i=0;i<n;i++) {//将排序后相等的字符串放在相同的vector string tmp=strs[i]; sort(tmp.begin(), tmp.end()); hash[tmp].push_back(strs[i]); } unordered_map<string, vector<string>>::iterator it; for(it=hash.begin();it != hash.end();it++) {//(3)将hash表中的value值(数组形式)放到结果数组 res.push_back(it->second); } return res; } };
相关文章推荐
- 第7周-项目1-求点类中距离的任务(1)成员函数
- Java技术_Java千百问(0025)_如何自定义异常
- 软件工程:黄金G点小游戏1.0
- SpringMVC源码剖析(三)- DispatcherServlet的初始化流程
- https://code.csdn.net/xiebaoyou/linux-4-3-0-comment
- MathProg语言简介(附带例子)
- 哈夫曼编码的生成
- android数据库SQLite(1)
- 远程传输文件,排除某个目录
- Maven教程
- Python--将内容写入文本文件中
- IIS ashx
- tomcat容器下读取配置文件
- List<Map<String, Object>>的循环
- 《数字图像处理原理与实践(MATLAB版)》一书之代码Part5
- js中ajax异步导致的一些问题
- 不使用中间变量交换两个数. 求平均数考虑溢出
- iOS7 StatusBar 使用小结
- GCJ 2009 Round2 Problem A. Crazy Rows
- java中static作用详解