dimanche 3 mai 2020

std::unordered_map::count is not working in my code

I have a doubt with the solution of this question which is stated below -

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note. Strings["aa", "ab"] should return false and strings["aa", "aab"] should return true according to question.

Here is the code which I have attempted in the first place and I'm not getting a required output as mentioned above.


        unordered_map<char,int>umap;

        for(char m:magazine)
        {
            umap[m]++;
        }

        for(char r:ransomNote)
        { 
            if(umap.count(r)<=1)
            {
                return false;
            }
            else{
                umap[r]--;
            }


        }
       return true; 
    }

In the above code, I have used umap.count(r)<=1 to return false if there is no key present. For the strings ["aa","aab"], it is returning true but for strings ["aa","ab"], it is also returning true but it should return false. Then I used another way to solve this problem by using just umap[r]<=0 in the place of umap.count(r)<=1 and it is working just fine and else all code is same.

bool canConstruct(string ransomNote, string magazine) {

        unordered_map<char,int>umap;

        for(char m:magazine)
        {
            umap[m]++;
        }

        for(char r:ransomNote)
        { 
            if(umap[r]<=0)
            {
                return false;
            }
            else{
                umap[r]--;
            }


        }
       return true; 
    }

I'm not able to get what i'm missing in the if condition of first code. Can anyone help me to state what I'm doing wrong in first code. Any help is appreciated.

Aucun commentaire:

Enregistrer un commentaire