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
}
相关推荐
lengxuenong4 分钟前
潍坊一中第四届编程挑战赛(初赛)题解
算法
松涛和鸣11 分钟前
25、数据结构:树与二叉树的概念、特性及递归实现
linux·开发语言·网络·数据结构·算法
Han.miracle22 分钟前
数据结构--初始数据结构
算法·集合·大o表示法
List<String> error_P23 分钟前
C语言联合体:内存共享的妙用
算法·联合体
little~钰34 分钟前
可持久化线段树和标记永久化
算法
王光环1 小时前
C语言写exe脚本
c语言·开发语言
獭.獭.1 小时前
C++ -- 二叉搜索树
数据结构·c++·算法·二叉搜索树
TOYOAUTOMATON1 小时前
自动化工业夹爪
大数据·人工智能·算法·目标检测·机器人
leoufung1 小时前
图解除法查询问题:用 C 语言和 DFS 实现带权有向图的路径乘积
c语言·开发语言·深度优先
雨落在了我的手上1 小时前
知识扩展:进制的详细介绍
c语言·学习