I know that many questions already pose this problem, but I want to do this using std::unordered_map
in c++. If someone has some answer similar to my implementation please point me to some link. Thanks.
I have used hashing as a way to count occurrences of the characters in a string and using that function to compare two strings if they have same number of same characters but I think I may have some issue in returning the correct prompt.
#include<iostream>
#include<bits/stdc++.h>
#include<string>
using namespace std;
unordered_map<char,int> countOccurences(string s){
unordered_map<char,int> m;
for(int c=0;c<s.length();c++){
if(s[c]!=' '){
//for type-insensitive counting
if((int)s[c] || (int)s[c] + 32){
m[s[c]]++;
}
}
}
return m;
}
int main(){
string s1,s2;
cout<<"Enter two strings to be checked:\n";
cin>>s1;
cin>>s2;
unordered_map<char,int> m1,m2;
m1 = countOccurences(s1);
m2 = countOccurences(s2);
for(int i=0;i<=255;i++){
if(m1[i]!=m2[i])
cout<<"Strings are not anagrams\n";
break;
return 0;
}
cout<<"Strings match\n";
return 0;
}
I expect output to be showing "Strings are not anagrams" but I am getting "Strings match"