-
Notifications
You must be signed in to change notification settings - Fork 101
/
anagram.cpp
71 lines (61 loc) · 1.85 KB
/
anagram.cpp
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
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 * 104
s and t consist of lowercase English letters.
*/
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.length()!=t.length()){
return false;
}
unordered_map<char,int> R;
vector<char> unique_r;
unordered_map<char,int> M;
vector<char> unique_m;
for(int i=0;i<s.length();i++){
if(R.count(s[i])>0){
R[s[i]]++;
}
else{
R[s[i]]=1;
unique_r.push_back(s[i]);
}
}
for(int i=0;i<t.length();i++){
if(M.count(t[i])>0){
M[t[i]]++;
}
else{
M[t[i]]=1;
unique_m.push_back(t[i]);
}
}
vector<char>::iterator it=unique_r.begin();
while(it!=unique_r.end()){
unordered_map<char,int>::iterator it1=R.find(*it);
unordered_map<char,int>::iterator it2=M.find(*it);
if(it2!=M.end()){
if(it1->first==it2->first && it2->second!=it1->second){
return false;
break;
}
}
else{
return false;
break;
}
it++;
}
return true;
}
};