首页 > 学院 > 开发设计 > 正文

【LeetCode】 49. Group Anagrams

2019-11-06 06:09:13
字体:
来源:转载
供稿:网友

题目描述

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.

解题思路

哈希。 将排好序的string作为key即可。

AC代码

class Solution {public: vector<vector<string>> groupAnagrams(vector<string>& strs) { map<string, vector<string>> table; for (int i = 0; i < strs.size(); ++i) { string curStr = strs[i]; sort(curStr.begin(), curStr.end()); table[curStr].push_back(strs[i]); } map<string, vector<string>>::iterator it; vector<vector<string>> ans; for (it = table.begin(); it != table.end(); ++it) { ans.push_back(it->second); } return ans; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表