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
}
相关推荐
MYX_3095 分钟前
第三章 线型神经网络
深度学习·神经网络·学习·算法
Code小翊1 小时前
C语言bsearch的使用
java·c语言·前端
坚持编程的菜鸟1 小时前
LeetCode每日一题——三角形的最大周长
算法·leetcode·职场和发展
Moniane2 小时前
FastGPT 与 MCP 协议概述
算法
草莓工作室3 小时前
数据结构7:栈和队列
c语言·数据结构
Meteor_cyx3 小时前
Day12 二叉树遍历
算法
加藤不太惠3 小时前
十大排序其六
算法·排序算法
前端小刘哥3 小时前
视频推拉流平台EasyDSS技术特点及多元应用场景剖析
算法
Brianna Home3 小时前
从零到一:用Godot打造2D游戏《丛林探险》
算法·游戏·性能优化·游戏引擎·bug·godot·动画
小欣加油3 小时前
leetcode 143 重排链表
数据结构·c++·算法·leetcode·链表