[LeetCode-String] Ransom Letter

Title description

Given a ransom letter (ransom) string and a magazine (magazine) string, determine whether the first string ransom can be composed of characters in the second string magazines. If it can be constructed, return true; otherwise return false.
(Title description: In order not to expose the handwriting of the ransom letter, you need to search the letters of the magazine to form words to express the meaning. Each character in the magazine string can only be used once in the ransom letter string.)
Note:
You It can be assumed that both strings contain only lowercase letters.
Examples:

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

Title link : https://leetcode-cn.com/problems/ransom-note/

Ideas

The meaning of this question is that there are two strings named ransom and magazine. To determine whether the characters in ransom appear in the magazine, and the characters in the magazine can only be used once, for example, ab appears in abcd, and aab does not appear in abcd because a in abcd can only match once. Therefore, first create a hash table to record the number of occurrences of each character in the magazine, traverse ransom, if a character appears in the magazine, if the value is 0, then return false, otherwise the hash value corresponding to the character minus one. code show as below

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        if(ransomNote.empty()) return true;
        if(ransomNote.length()>magazine.length()) return false;
        
        int mg[256];
        memset(mg, 0, sizeof(mg));
        for(int i=0; i<magazine.length(); i++){
            mg[magazine[i]]++;
        }
        for(int i=0; i<ransomNote.length(); i++){
            if(mg[ransomNote[i]]>0){
                mg[ransomNote[i]]--;
            } else return false;
        }
        return true;
    }
};
  • Time complexity: O (m + n)
    where m and n are the length of the two strings.
  • Space complexity: O (1)

Guess you like

Origin www.cnblogs.com/flix/p/12688018.html