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
}
相关推荐
wwww.bo6 分钟前
机器学习(决策树)
算法·决策树·机器学习
辞--忧11 分钟前
深入浅出决策树
算法·决策树·机器学习
Y2003091611 分钟前
决策树总结
算法·决策树·机器学习
lynn8570_blog11 分钟前
低端设备加载webp ANR
前端·算法
图灵学术计算机论文辅导1 小时前
论文推荐|迁移学习+多模态特征融合
论文阅读·人工智能·深度学习·计算机网络·算法·计算机视觉·目标跟踪
threejs源码翻译官2 小时前
显微镜图像处理【优化】- 使用图像风格迁移技术放大图像细节
算法
前路不黑暗@2 小时前
C语言:操作符详解(二)
c语言·开发语言·经验分享·笔记·学习·学习方法·visual studio
强德亨上校2 小时前
贪心算法(Greedy Algorithm)详解
算法·贪心算法
浮灯Foden3 小时前
算法-每日一题(DAY13)两数之和
开发语言·数据结构·c++·算法·leetcode·面试·散列表
西工程小巴4 小时前
实践笔记-VSCode与IDE同步问题解决指南;程序总是进入中断服务程序。
c语言·算法·嵌入式