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
}
相关推荐
Navigator_Z1 小时前
LeetCode //C - 1240. Tiling a Rectangle with the Fewest Squares
c语言·算法·leetcode
稻米哟1 小时前
力扣100——双指针
算法·leetcode
码行山野赴时序归途1 小时前
C语言预处理指令:编译前的“幕后导演“
c语言·开发语言
明志数科2 小时前
具身智能真机采集工程实践:5类高频失效模式与规避清单
人工智能·算法·机器学习
CSDN_RTKLIB2 小时前
空间哈希与拓扑缓存
算法
大熊背4 小时前
IspPipeline色相旋转模块实现
人工智能·算法·计算机视觉
爱学习的小白柏4 小时前
同城双活的核心不是双活,是逼着数据别出机房
大数据·人工智能·算法·langchain·ai编程
鹿角片ljp4 小时前
LeetCode 31:下一个排列|右找小,右找大,交换,右反转
java·数据结构·算法
2401_858286114 小时前
130.【C语言】可变参数宏
c语言·开发语言
彧azz5 小时前
B树原理与C语言实现
c语言·数据结构·b树