【力扣每日一题】力扣383赎金信

题目来源

力扣383赎金信

题目概述

给你两个字符串:ransomNotemagazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。 如果可以,返回 true ;否则返回 falsemagazine 中的每个字符只能在 ransomNote 中使用一次。

示例

示例 1:

输入:ransomNote = "a", magazine = "b"

输出:false

示例 2:

输入:ransomNote = "aa", magazine = "ab"

输出:false

示例 3:

输入:ransomNote = "aa", magazine = "aab"

输出:true

提示

  • 1 <= ransomNote.length, magazine.length <= 10^5
  • ransomNote 和 magazine 由小写英文字母组成

思路分析

这个题目挺简单的,用一个长度为26的数组记录每个字母出现的次数,对比ransomNote中的字母及次数是否不大于magazine中对应字母出现的次数即可。

代码实现

java实现

java 复制代码
public class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        int rLength = ransomNote.length();
        int mLength = magazine.length();
        if (rLength > mLength) {
            return false;
        }
        int[] rest = new int[26];
        int count = 0;
        for(int i = 0; i < rLength; i++) {
            rest[ransomNote.charAt(i) - 'a']++;
            count++;
        }
        for (int i = 0; i < mLength; i++) {
            int current = magazine.charAt(i) - 'a';
            if (rest[current] > 0) {
                count--;
                if (count == 0) {
                    return true;
                }
            }
            rest[current]--;
        }
        return false;
    }

}

c++实现

cpp 复制代码
class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        int rLength = ransomNote.length();
        int mLength = magazine.length();
        if (rLength > mLength) return false;

        int rest[26] = { 0 };
        int count = 0;
        for (int i = 0; i < rLength; i++) {
            rest[ransomNote[i] - 'a']++;
            count++;
        }
        for (int i = 0; i < mLength; i++) {
            int current = magazine[i] - 'a';
            if (rest[current] > 0){
                if ((--count)==0) {
                    return true;
                }
            }
            rest[current]--;
        }
        return false;
    }
};
相关推荐
血色橄榄枝9 分钟前
基于用户注册信息的关键词检测挑战赛「Datawhale AI 夏令营」
人工智能·算法·机器学习
Cx330❀1 小时前
【MySQL基础】一文吃透“表的约束”:从 Null/Default 到主外键的终极安全法则
linux·服务器·数据库·c++·mysql·安全
Java搬码工1 小时前
CompletableFuture 完整详解 + 全场景使用案例
java
许心月1 小时前
Java学习资料网站汇总
java
c238561 小时前
第二篇:《测试指挥官:可视化单题自测框架(含 assert 实操)》
java·数据库·c++·算法·安全性测试
辞旧 lekkk1 小时前
【Redis初阶】常见数据类型
开发语言·数据库·c++·redis·学习·缓存·bootstrap
帅次2 小时前
Kotlin 与 Java 互操作:混合工程里的平台类型与 API 边界
java·开发语言·kotlin·suspend·nullable
六点_dn2 小时前
Linux学习笔记-printf命令
linux·运维·算法
X-⃢_⃢-X2 小时前
一、第一阶段:认识 Spring Boot
java·spring boot·后端
前端工作日常2 小时前
我学习到的Java程序的生命周期
java·后端