LeetCode //C - 383. Ransom Note

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:

Input: ransomNote = "a", magazine = "b"
Output: false

Example 2:

Input: ransomNote = "aa", magazine = "ab"
Output: false

Example 3:

Input: ransomNote = "aa", magazine = "aab"
Output: true

Constraints:
  • 1 <= ransomNote.length, magazine.length <= 1 0 5 10^5 105
  • ransomNote and magazine consist of lowercase English letters.

From: LeetCode

Link: 383. Ransom Note


Solution:

Ideas:

In this function, magazineLetters is an array of 26 integers (for each letter in the English alphabet), initialized to 0. We first count the frequency of each letter in magazine. Then, for each letter in ransomNote, we check if it exists in magazine (by checking magazineLetters). If it exists, we decrement its count; otherwise, we return false. If all letters in ransomNote are successfully found in magazine, we return true.

Code:
c 复制代码
bool canConstruct(char* ransomNote, char* magazine) {
    int magazineLetters[26] = {0}; // Array to store the frequency of each letter in magazine

    // Count the frequency of each letter in magazine
    for (int i = 0; magazine[i] != '\0'; i++) {
        magazineLetters[magazine[i] - 'a']++;
    }

    // Check if each letter in ransomNote can be constructed from magazine
    for (int i = 0; ransomNote[i] != '\0'; i++) {
        if (magazineLetters[ransomNote[i] - 'a'] > 0) {
            magazineLetters[ransomNote[i] - 'a']--; // Use the letter and decrement its count
        } else {
            return false; // If a letter in ransomNote is not found in magazine, return false
        }
    }

    return true; // All letters in ransomNote are found in magazine
}
相关推荐
千金裘换酒1 分钟前
LeetCode 数组经典题刷题
算法·leetcode·职场和发展
fie88891 小时前
MATLAB有限元框架程序
python·算法·matlab
小郭团队1 小时前
1_5_五段式SVPWM (传统算法反正切+DPWM1)算法理论与 MATLAB 实现详解
人工智能·嵌入式硬件·算法·dsp开发
sycmancia1 小时前
C语言学习03——数据类型
c语言
思成Codes1 小时前
ACM训练:接雨水3.0——动态接雨水
数据结构·算法
alphaTao1 小时前
LeetCode 每日一题 2026/1/12-2026/1/18
python·算法·leetcode
sin_hielo1 小时前
leetcode 2943
数据结构·算法·leetcode
Snow_day.2 小时前
有关平衡树
数据结构·算法·贪心算法·动态规划·图论
Hcoco_me2 小时前
大模型面试题75:讲解一下GRPO的数据回放
人工智能·深度学习·算法·机器学习·vllm
Xの哲學2 小时前
Linux设备驱动模型深度解剖: 从设计哲学到实战演练
linux·服务器·网络·算法·边缘计算