标签:logs 字符串排序 nat std not cond val 结果 div
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: All inputs will be in lower-case.
很明显,这个题目要求将字母相同的单词归为一组。
判断字符串中字符相同一般有两种方法:
具体到本题中,可以将字符串排序后的结果作为key,vector<string>作为value,使用map<key, vector<string>>,每个key对应的vector<string>就是同一组单词。
class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string>> res; if (strs.empty()) return res; unordered_map<string, vector<string>> container; for (auto str : strs) { string tmp(str); std::sort(tmp.begin(), tmp.end()); (container[tmp]).push_back(str); } for (auto ele : container) res.push_back(ele.second); return res; } };
标签:logs 字符串排序 nat std not cond val 结果 div
原文地址:http://www.cnblogs.com/naivecoder/p/7010611.html