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
}
相关推荐
c++逐梦人7 分钟前
DFS剪枝与优化
算法·深度优先·剪枝
量化炼金 (CodeAlchemy)9 分钟前
【交易策略】基于随机森林的市场结构预测:机器学习在量化交易中的实战应用
算法·随机森林·机器学习
coder_Eight22 分钟前
LRU 缓存实现详解:双向链表 + 哈希表
前端·算法
重生之我是Java开发战士27 分钟前
【动态规划】路径问题:不同路径,珠宝的最高价值,下降路径最小和,最小路径和,地下城游戏
算法·游戏·动态规划
小辉同志33 分钟前
739. 每日温度
c++·算法·leetcode
Via_Neo43 分钟前
二进制枚举
数据结构·算法·leetcode
荣光属于凯撒1 小时前
P3040 [USACO12JAN] Bale Share S
算法·深度优先
kingcjh971 小时前
十、RL 算法性能调优指南
深度学习·算法
爱编码的小八嘎1 小时前
C语言完美演绎6-14
c语言
muls11 小时前
java面试宝典
java·linux·服务器·网络·算法·操作系统