[leetcode][hash] Anagrams
来源:互联网 发布:旅游软件排行 编辑:程序博客网 时间:2024/05/16 08:31
题目;
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
v1 76msclass Solution {public: //将单词按字母顺序排序后作为hash的key,字符串在strs中的下标组成的vector作为valuevector<string> anagrams(vector<string>& strs) {vector<string> res;map<string, vector<int> > hashTable;for (int i = 0; i < strs.size(); ++i){string s = strs[i];sort(s.begin(), s.end());map<string, vector<int> >::iterator iter = hashTable.find(s);if (iter != hashTable.end()){(iter->second).push_back(i);}else{vector<int> vTmp;vTmp.push_back(i);hashTable[s] = vTmp;}}for (map<string, vector<int> >::iterator iter = hashTable.begin(); iter != hashTable.end(); ++iter){if ((iter->second).size() > 1){for (int i = 0; i < (iter->second).size(); ++i){res.push_back(strs[(iter->second)[i]]);}}}return res;}};
class Solution {public://将单词按字母顺序排序后作为hash的key,value等于排序后单词第一次出现大的下标,当第二次出现时value置为-1防止重复再结果中插入第一出现的单词vector<string> anagrams(vector<string>& strs) {vector<string> res;map<string, int> hashTable;for (int i = 0; i < strs.size(); ++i){string s = strs[i];sort(s.begin(), s.end());map<string,int>::iterator iter = hashTable.find(s);if (iter != hashTable.end()){if (iter->second != -1){res.push_back(strs[iter->second]);iter->second = -1;}res.push_back(strs[i]);}else{hashTable[s] = i;}}return res;}};
v3 40ms
class Solution {public:const int alphabetList[26] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101 };vector<string> anagrams(vector<string>& strs) {vector<string> res;map<long long, int> hashTable;for (int i = 0; i < strs.size(); ++i){long long multi = 1;for (int j = 0; j < strs[i].size(); ++j){multi *= alphabetList[strs[i][j]-'a'];}map<long long, int>::iterator iter = hashTable.find(multi);if (iter != hashTable.end()){if (iter->second != -1){res.push_back(strs[iter->second]);iter->second = -1;}res.push_back(strs[i]);}else{hashTable[multi] = i;}}return res;}};
每一个字母用一个质数代表,用单词中每个字符对应的质数相乘的积作为hash的key(这样查找时不需要比较单词的每一个字符,效率大大提高了),value的意义同上
0 0
- LeetCode[Hash Table]: Anagrams
- [leetcode][hash] Anagrams
- LeetCode *** 49. Group Anagrams (Hash Table)
- LeetCode-Hash-438. Find All Anagrams in a String
- LeetCode: Anagrams
- LeetCode: Anagrams
- LeetCode Anagrams
- Leetcode: Anagrams
- [Leetcode] Anagrams
- LeetCode : Anagrams
- [leetcode] anagrams
- LeetCode Anagrams
- [LeetCode] Anagrams
- [LeetCode]Anagrams
- [leetcode]Anagrams
- leetcode anagrams
- [leetcode] Anagrams
- LeetCode-Anagrams
- MySQL 5.6 for Windows 解压缩版配置安装
- Tomcat源码学习——第1章
- iOS ibeacon后台运行相关文章
- Linux基础必懂:eth0,eth1,eth2,lo是什么意思?
- linux下qt使用svn的问题
- [leetcode][hash] Anagrams
- Android Fragment详解
- Android手机的休眠状态
- 怎样在Swift中使用CocoaPods
- shell文件读取及字符串分隔符
- 统计图形-茎叶图
- js常用函数-1
- Understanding the Objective-C Runtime
- ARM中断笔记