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
}
相关推荐
好奇龙猫8 分钟前
【学习AI-相关路程-mnist手写数字分类-win-硬件:windows-自我学习AI-实验步骤-全连接神经网络(BPnetwork)-操作流程(3) 】
人工智能·算法
sp_fyf_202444 分钟前
计算机前沿技术-人工智能算法-大语言模型-最新研究进展-2024-11-01
人工智能·深度学习·神经网络·算法·机器学习·语言模型·数据挖掘
香菜大丸1 小时前
链表的归并排序
数据结构·算法·链表
jrrz08281 小时前
LeetCode 热题100(七)【链表】(1)
数据结构·c++·算法·leetcode·链表
oliveira-time1 小时前
golang学习2
算法
南宫生2 小时前
贪心算法习题其四【力扣】【算法学习day.21】
学习·算法·leetcode·链表·贪心算法
懒惰才能让科技进步3 小时前
从零学习大模型(十二)-----基于梯度的重要性剪枝(Gradient-based Pruning)
人工智能·深度学习·学习·算法·chatgpt·transformer·剪枝
DARLING Zero two♡3 小时前
关于我、重生到500年前凭借C语言改变世界科技vlog.16——万字详解指针概念及技巧
c语言·开发语言·科技
Ni-Guvara3 小时前
函数对象笔记
c++·算法
泉崎4 小时前
11.7比赛总结
数据结构·算法