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
}
相关推荐
keep intensify17 分钟前
数据结构---单链表的增删查改
c语言·数据结构·c++·经验分享·学习·算法·分享
算法歌者20 分钟前
[C]基础13.深入理解指针(5)
c语言
opple6632 分钟前
力扣-数据结构-二叉树
数据结构·算法·leetcode
XWXnb61 小时前
STM32 中断系统深度剖析
c语言·开发语言·stm32·嵌入式硬件
import_random1 小时前
[社交网络]布局算法(可视化)
算法
大模型铲屎官1 小时前
Unity C# 与 Shader 交互入门:脚本动态控制材质与视觉效果 (含 MaterialPropertyBlock 详解)(Day 38)
c语言·unity·c#·交互·游戏开发·材质·shader
地平线开发者1 小时前
C++ 部署的性能优化方法
c++·算法·自动驾驶
怀念无所不能的你1 小时前
acwing背包问题求方案数
学习·算法·动态规划·dp
Yingye Zhu(HPXXZYY)2 小时前
洛谷P12238 [蓝桥杯 2023 国 Java A] 单词分类
c++·算法·蓝桥杯
积极向上的向日葵3 小时前
链表的中间节点
数据结构·算法·链表·快慢指针