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
}
相关推荐
折哥的程序人生 · 物流技术专研5 小时前
Java面试85题图解版 · 特别篇:2026后端高频面试题复盘(算法底层逻辑+高并发架构设计全解析,附Java实战代码)
java·网络·数据库·算法·面试
玖玥拾6 小时前
C/C++ 基础笔记(十四)多态与模板编程
c语言·c++·多态·模板
想吃火锅10056 小时前
【leetcode】14.最长公共前缀js
算法·leetcode·职场和发展
云絮.8 小时前
数据库操作
数据库·mysql·算法·oracle
小林ixn8 小时前
LeetCode 206. 反转链表(迭代 + 递归详解)
算法·leetcode·链表
凡人叶枫8 小时前
Effective C++ 条款17:以独立语句将 newed 对象置入智能指针
java·linux·开发语言·c++·算法
菜鸟‍9 小时前
LeetCode 1 27 和 704 || 两数之和 移除元素 二分查找
算法·leetcode·职场和发展
caimouse10 小时前
Reactos 第1章 概述
c语言·开发语言·架构
退休倒计时11 小时前
【每日一题】LeetCode 142. 环形链表 II TypeScript
算法·leetcode·链表·typescript
啊森要自信11 小时前
【GUI自动化测试】控件、鼠标键盘操作与多场景自动化
c语言·开发语言·python·adb·ipython