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
}
相关推荐
皓月斯语33 分钟前
B3849 [GESP样题 三级] 进制转换 题解
c++·算法·题解
天空'之城36 分钟前
C 语言工业级通用组件 02:通用内存池
c语言·嵌入式·内存管理·内存池
中微极客42 分钟前
剪枝与量化:让YOLO在边缘设备上高效部署
算法·yolo·剪枝
牢姐与蒯1 小时前
双指针算法
数据结构·算法
Hesionberger1 小时前
LeetCode406:重建身高队列精髓解析
开发语言·数据结构·python·算法·leetcode
不要葱花2 小时前
接下来我将复现 10 篇强化学习算法:第 3 篇,一杯喜茶,搞定 Search-R1
算法·面试
十月的皮皮2 小时前
C语言学习笔记20260717-预处理机制
c语言·笔记·学习
geovindu2 小时前
CSharp: Recursion Algorithm
开发语言·后端·算法·c#·递归算法
z小猫不吃鱼2 小时前
ResRep: Lossless CNN Pruning via Decoupling Remembering and Forgetting
算法·cnn·剪枝