Easy C++ without using map


  • 0
    H

    The logic is straightforward. We can only use a letter only once from magazine. Instead of creating the map, we could simply remove the matched letter from magazine and keep searching in ransomNote.

    class Solution {
    public:
        bool canConstruct(string ransomNote, string magazine) {
            for(char c : ransomNote){
                if(magazine.find(c) != string::npos){
                    magazine.erase(magazine.find(c),1);
                }else{
                    return false;
                }
            }
            
            return true;
        }
    };
    
    

  • 0
    M

    Do you know if it's faster to use erase() n times than to create a map?


  • 0
    H

    @mi2307 Thanks for your comment. It is must faster to use map. This is just one solution without additional memory usage.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.