Header Ad

Leetcode Ransom Note problem solution

In this Leetcode Ransom Note problem solution you have given two stings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise. Each letter in magazine can only be used once in ransomNote.

Leetcode Ransom Note problem solution


Problem solution in Python.

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        note,mag = Counter(ransomNote), Counter(magazine)
        if note & mag == note: return True
        return False



Problem solution in Java.

class Solution {
    public boolean canConstruct(String ransomeNote, String magazine) {
        HashMap<Character,Integer> hashmap = new HashMap<>();
        for(int i=0;i<magazine.length();i++)
        {
            if(!hashmap.containsKey(magazine.charAt(i)))
                hashmap.put(magazine.charAt(i),1);
            else
                hashmap.put(magazine.charAt(i),hashmap.get(magazine.charAt(i))+1);
        }
        
        int start=0;
        while(start<ransomeNote.length())
        {
            if(!hashmap.containsKey(ransomeNote.charAt(start)))
                return false;
            else
            {
                hashmap.put(ransomeNote.charAt(start),hashmap.get(ransomeNote.charAt(start))-1);
                if(hashmap.get(ransomeNote.charAt(start))==0)
                    hashmap.remove(ransomeNote.charAt(start));
            }
            
            start++;
        }
        return true;
    }
}


Problem solution in C++.

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        int r[26] = {0};
        int m[26] = {0};
        
        for(auto c : ransomNote)    r[c - 'a']++;
        for(auto c : magazine)      m[c - 'a']++;
        for(int i = 0; i < 26; i++) if(r[i] > m[i]) return false;
        return true;
    }
};


Problem solution in C.

bool canConstruct(char * ransomNote, char * magazine){

int t[26] = {0};

for(char *str = magazine; *str; str++ ) {
    if(*str >= 97 && *str <= 122) {
        t[*str - 97] += 1;
    }
}

for(char *str = ransomNote; *str; str++) {
    if(t[*str -97] == 0)
        return false;
    else if (t[*str -97] > 0)
        t[*str -97] -= 1;
}

return true;
}


Post a Comment

0 Comments