-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
64 lines (60 loc) · 1.56 KB
/
main.cpp
File metadata and controls
64 lines (60 loc) · 1.56 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
57
58
59
60
61
62
63
64
#include "iostream"
#include "map"
using namespace std;
// class Solution
// {
// public:
// bool isAnagram(string s, string t)
// {
// if(s.length() != t.length()) return false;
// int n = s.length();
// int count[26] = {0};
// for(int i = 0; i < n; i++)
// {
// count[s[i]-'a']++;
// count[t[i]-'a']--;
// }
// for(int i = 0; i < 26; i++)
// if(count[i]) return false;
// return true;
// }
// };
class Solution
{
public:
bool isAnagram(string s, string t)
{
if ((int)s.length() != (int)t.length())
return false;
map<char, int> dictionary = {};
for (char el: s)
{
if (dictionary.find(el) != dictionary.end())
dictionary[el]++;
else
dictionary.insert(pair<char, int>{el, 1});
}
// for (pair<char, int> pair: dictionary)
// cout << "Char: " << pair.first << "; Count: " << pair.second << endl;
for (char el: t)
{
if (dictionary.find(el) != dictionary.end())
dictionary[el]--;
else
return false;
}
for (pair<char, int> pair: dictionary)
if (pair.second != 0)
return false;
return true;
}
};
int main()
{
Solution sol;
string s = "anagram";
string t = "nagaram";
// sol.isAnagram(s, t);
cout << "Is " << s << " a valid anagram of " << t << "? Answer: " << sol.isAnagram(s, t) << endl;
return 0;
}