【力扣每日一题】力扣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;
    }
};
相关推荐
不吃洋葱.1 分钟前
前缀和|差分
数据结构·算法
张先shen6 分钟前
Elasticsearch RESTful API入门:全文搜索实战(Java版)
java·大数据·elasticsearch·搜索引擎·全文检索·restful
_Chipen27 分钟前
C++基础问题
开发语言·c++
灿烂阳光g31 分钟前
OpenGL 2. 着色器
c++·opengl
天河归来1 小时前
springboot框架redis开启管道批量写入数据
java·spring boot·redis
张先shen1 小时前
Elasticsearch RESTful API入门:全文搜索实战
java·大数据·elasticsearch·搜索引擎·全文检索·restful
codervibe1 小时前
如何用 Spring Security 构建无状态权限控制系统(含角色菜单控制)
java·后端
codervibe1 小时前
项目中如何用策略模式实现多角色登录解耦?(附实战代码)
java·后端
TCChzp1 小时前
synchronized全链路解析:从字节码到JVM内核的锁实现与升级策略
java·jvm
大葱白菜1 小时前
🧩 Java 枚举详解:从基础到实战,掌握类型安全与优雅设计
java·程序员