-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnagrams_using_Hashmaps
66 lines (54 loc) · 1.35 KB
/
Anagrams_using_Hashmaps
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
#include <bits/stdc++.h>
using namespace std;
// Function to check if two strings are anagrams
bool areAnagrams(string s1, string s2)
{
// If lengths are different, they cannot be anagrams
if (s1.length() != s2.length()) {
return false;
}
// Create a hashmap to store character frequencies
unordered_map<char, int> charCount;
// Count frequency of each character in the first string
for (char c : s1) {
charCount[c]++;
}
// Decrement frequency of each character in the second
// string
for (char c : s2) {
// If character not found in hashmap, return false
if (charCount.find(c) == charCount.end()
|| charCount[c] == 0) {
return false;
}
charCount[c]--;
}
// Check if all frequencies are zero
for (auto& pair : charCount) {
if (pair.second != 0) {
return false;
}
}
// If all conditions satisfied, they are anagrams
return true;
}
int main()
{
string str1 = "listen";
string str2 = "silent";
if (areAnagrams(str1, str2)) {
cout << "True" << endl;
}
else {
cout << "False" << endl;
}
str1 = "gram";
str2 = "arm";
if (areAnagrams(str1, str2)) {
cout << "True" << endl;
}
else {
cout << "False" << endl;
}
return 0;
}