valid-anagram 1.0.0
Valid Anagram
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include "iostream"
2#include "map"
3
4using namespace std;
5
6// class Solution
7// {
8// public:
9// bool isAnagram(string s, string t)
10// {
11// if(s.length() != t.length()) return false;
12// int n = s.length();
13// int count[26] = {0};
14// for(int i = 0; i < n; i++)
15// {
16// count[s[i]-'a']++;
17// count[t[i]-'a']--;
18// }
19// for(int i = 0; i < 26; i++)
20// if(count[i]) return false;
21// return true;
22// }
23// };
24
26{
27public:
28 bool isAnagram(string s, string t)
29 {
30 if ((int)s.length() != (int)t.length())
31 return false;
32 map<char, int> dictionary = {};
33 for (char el: s)
34 {
35 if (dictionary.find(el) != dictionary.end())
36 dictionary[el]++;
37 else
38 dictionary.insert(pair<char, int>{el, 1});
39 }
40 // for (pair<char, int> pair: dictionary)
41 // cout << "Char: " << pair.first << "; Count: " << pair.second << endl;
42 for (char el: t)
43 {
44 if (dictionary.find(el) != dictionary.end())
45 dictionary[el]--;
46 else
47 return false;
48 }
49 for (pair<char, int> pair: dictionary)
50 if (pair.second != 0)
51 return false;
52 return true;
53 }
54};
55
56int main()
57{
58 Solution sol;
59 string s = "anagram";
60 string t = "nagaram";
61 // sol.isAnagram(s, t);
62 cout << "Is " << s << " a valid anagram of " << t << "? Answer: " << sol.isAnagram(s, t) << endl;
63 return 0;
64}
bool isAnagram(string s, string t)
Definition main.cpp:28
int main()
Definition main.cpp:56