0
点赞
收藏
分享

微信扫一扫

LeetCode //C - 383. Ransom Note

萍儿的小确幸 2023-08-13 阅读 41

383. Ransom Note

Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.

Each letter in magazine can only be used once in ransomNote.
 

Example 1:

Example 2:

Example 3:

Constraints:

  • 1 < = r a n s o m N o t e . l e n g t h , m a g a z i n e . l e n g t h < = 1 0 5 1 <= ransomNote.length, magazine.length <= 10^5 1<=ransomNote.length,magazine.length<=105
  • ransomNote and magazine consist of lowercase English letters.

From: LeetCode
Link: 383. Ransom Note


Solution:

Ideas:
  1. It first creates an array magazineCount of size 26 (for each lowercase letter of the alphabet) and initializes all values to 0.

  2. It then loops over each character in the ransomNote string, increments the corresponding count in the magazineCount array based on ASCII value of each character. Here, ransomNote[i] - ‘a’ gives the index in the array corresponding to the character. For instance, if ransomNote[i] is ‘a’, then ransomNote[i] - ‘a’ is 0, which is the index for ‘a’. If ransomNote[i] is ‘b’, then ransomNote[i] - ‘a’ is 1, which is the index for ‘b’, and so on.

  3. After that, it loops over each character in the magazine string. For each character, it decrements the count in the magazineCount array. If at any point, the count becomes less than 0, it means that there are more occurrences of that character in the ransom note than there are in the magazine. In such a case, it immediately returns false, indicating that the ransom note cannot be formed.

  4. If the function doesn’t return false during the second loop, it means that all characters in the ransom note are present in the magazine in at least the required quantities. So, it returns true at the end, indicating that the ransom note can be formed from the magazine.

Code:
bool canConstruct(char * ransomNote, char * magazine){
    int magazineCount[26] = {0};
    
    for (int i = 0; ransomNote[i] != '\0'; i++) {
        magazineCount[ransomNote[i] - 'a']++;
    }
    
    for (int i = 0; magazine[i] != '\0'; i++) {
        magazineCount[magazine[i] - 'a']--;
        if (magazineCount[magazine[i] - 'a'] < 0) {
            return false;
        }
    }
    
    return true;
}
举报

相关推荐

0 条评论