harshrd
harshrd

Reputation: 79

Determine two strings if they are anagrams using unordered_map

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"

Upvotes: 0

Views: 591

Answers (1)

Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31215

You are missing curly braces on the if statement here :

    if(m1[i]!=m2[i])
        cout<<"Strings are not anagrams\n";
        break;
        return 0;

So the code is equivalent to :

for(int i=0;i<=255;i++){
    if(m1[i]!=m2[i]) {
        cout<<"Strings are not anagrams\n";
    }
    break;
    return 0;
}

After the first comparison, the break statement is always reached, exiting the for loop.

You should replace it with :

for(int i=0;i<=255;i++){
    if(m1[i]!=m2[i]) {
        cout<<"Strings are not anagrams\n";
        return 0;
    }
}

Also, as stated in the question's comments, the case-sensitive test is weird, as if((int)s[c] will always be true.

You might want to write it like this instead :

for(int c=0;c<s.length();c++){ 
    if(s[c]!=' '){
        m[std::toupper(s[c])]++;
    }
}

Upvotes: 1

Related Questions