-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
56 lines (50 loc) · 1.52 KB
/
main.cpp
File metadata and controls
56 lines (50 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Source: https://leetcode.com/problems/group-anagrams
// Title: Group Anagrams
// Difficulty: Medium
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Given two strings `s` and `t`, return `true` if `t` is an <button type="button" aria-haspopup="dialog" aria-expanded="false" aria-controls="radix-:rs:" data-state="closed" class="">anagram</button> of `s`, and `false` otherwise.
//
// **Example 1:**
//
// ```
// Input: s = "anagram", t = "nagaram"
// Output: true
// ```
//
// **Example 2:**
//
// ```
// Input: s = "rat", t = "car"
// Output: false
// ```
//
// **Constraints:**
//
// - `1 <= s.length, t.length <= 5 * 10^4`
// - `s` and `t` consist of lowercase English letters.
//
// **Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <unordered_map>
#include <vector>
using namespace std;
// Use sort + hashmap
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> groups;
for (auto& str : strs) {
auto key = str;
sort(key.begin(), key.end());
groups[key].push_back(str);
}
vector<vector<string>> ans;
for (auto& [_, vals] : groups) {
ans.push_back(vals);
}
return ans;
}
};