Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Using C++ Given an arbitrary ransom note, consisting of 15 20 words and several

ID: 3801359 • Letter: U

Question

Using C++

Given an arbitrary ransom note, consisting of 15 20 words and several magazines, write a function that will return a true, if the ransom note can be constructed from the words in the magazines, otherwise it will return a false. Each word in the magazines can only be used once in your ransom note. The algorithm should work efficiently, such as, utilizing hash tables for storing and looking up strings. An example hash function maybe the sum of the ascii values of all the characters in the string, modulus an appropriate positive integer. Utilize the built in string class, and some of its methods. For testing the code, utilize the ransom note and the magazines provided in files RansomNote.dat, Magazine1.dat, Magazine2.dat, Magazine3.dat, Magazine4.dat, Magazine5.datand Magazine6.dat.

Explanation / Answer

class Solution(object): def canConstruct(self, ransomNote, magazine): """ :type ransomNote: str :type magazine: str :rtype: bool """ counts = [0] * 26 letters = 0 for c in ransomNote: if counts[ord(c) - ord('a')] == 0: letters += 1 counts[ord(c) - ord('a')] += 1 for c in magazine: counts[ord(c) - ord('a')] -= 1 if counts[ord(c) - ord('a')] == 0: letters -= 1 if letters == 0: break return letters == 0 # Time: O(n) # Space: O(1) import collections class Solution2(object): def canConstruct(self, ransomNote, magazine): """ :type ransomNote: str :type magazine: str :rtype: bool """ return not collections.Counter(ransomNote) - collections.Counter(magazine)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote