标签:遍历 解法 begin cond tco 字符串 span ble solution
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ]
Note:
解法:
首先遍历输入,同时对每个string按 字典序 排序;(为了使相同字母异构 经hashtable映射得到相同的值)
排序后相同的value 进入同一个字符数组
核心在于排序
class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { unordered_map<string,vector<string>> m; vector<vector<string>> res; for(int i = 0; i < strs.size(); i++){ string s = strs[i]; sort(s.begin(),s.end());// 先对每个字符串排序 m[s].push_back(strs[i]); // 相同字母异构的字符串 经排序后 原来的异构字符串被 映射到一个同一个位置, //并用string存储原来的值 } for(auto ss : m){ vector<string> level = ss.second; res.push_back(level); } return res; } };
LeetCode 49. Group Anagrams HashTable
标签:遍历 解法 begin cond tco 字符串 span ble solution
原文地址:https://www.cnblogs.com/dingxi/p/11571300.html