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
}
相关推荐
卑微小文几秒前
企业级IP代理安全防护:数据泄露风险的5个关键防御点
前端·后端·算法
Erik_LinX25 分钟前
算法日记36:leetcode095最长公共子序列(线性DP)
算法
2301_7665360527 分钟前
刷leetcode hot100--动态规划3.11
算法·leetcode·动态规划
VT.馒头27 分钟前
【力扣】2629. 复合函数——函数组合
前端·javascript·算法·leetcode
DOMINICHZL38 分钟前
卡尔曼滤波算法从理论到实践:在STM32中的嵌入式实现
stm32·嵌入式硬件·算法
CodeJourney.1 小时前
光储直流微电网:能源转型的关键力量
数据库·人工智能·算法·能源
GUOYUGRA1 小时前
高纯氢能源在线监测分析系统组成和作用
人工智能·算法·机器学习
是星辰吖~1 小时前
C语言_数据结构_队列
c语言·数据结构
Chenyu_3101 小时前
05.基于 TCP 的远程计算器:从协议设计到高并发实现
linux·网络·c++·vscode·网络协议·tcp/ip·算法
论迹2 小时前
【二分算法】-- 三种二分模板总结
java·开发语言·算法·leetcode