LeetCode (Group Anagrams)

xiaoxiao2021-02-27  172

Problem:

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.

Solution:

class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { if (strs.empty() || strs.size() == 1) return {strs}; vector<vector<string>> ans; unordered_map<string, vector<string>> m; for (string s : strs){ string s1 = s; sort(s1.begin(), s1.end()); m[s1].push_back(s); } unordered_map<string, vector<string>>::iterator it; for (it = m.begin(); it != m.end(); it++){ ans.push_back(it->second); } return ans; } };

转载请注明原文地址: https://www.6miu.com/read-13854.html

最新回复(0)