-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathCheck_anagarams.cpp
69 lines (63 loc) · 1.61 KB
/
Check_anagarams.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
// C++ implementation of the approach
// Function that returns true if a and b
// are anagarams of each other
#include <bits/stdc++.h>
using namespace std;
bool isAnagram(string a, string b)
{
// Check if length of both strings is same or not
if (a.length() != b.length()) {
return false;
}
// Create a HashMap containing Character as Key and
// Integer as Value. We will be storing character as
// Key and count of character as Value.
unordered_map<char, int> Map;
// Loop over all character of String a and put in
// HashMap.
for (int i = 0; i < a.length(); i++) {
Map[a[i]]++;
}
// Now loop over String b
for (int i = 0; i < b.length(); i++) {
// Check if current character already exists in
// HashMap/map
if (Map.find(b[i]) != Map.end()) {
// If contains reduce count of that
// character by 1 to indicate that current
// character has been already counted as
// idea here is to check if in last count of
// all characters in last is zero which
// means all characters in String a are
// present in String b.
Map[b[i]] -= 1;
}
else {
return false;
}
}
// Loop over all keys and check if all keys are 0.
// If so it means it is anagram.
for (auto items : Map) {
if (items.second != 0) {
return false;
}
}
// Returning True as all keys are zero
return true;
}
// Driver code
int main()
{
string str1 = "gram";
string str2 = "arm";
// Function call
if (isAnagram(str1, str2))
cout << "The two strings are anagram of each other"
<< endl;
else
cout << "The two strings are not anagram of each "
"other"
<< endl;
}
// This code is contributed by shinjanpatra