Leetcode刷题100天—383. 赎金信( 数组)—day79

前言:

作者:神的孩子在歌唱

大家好,我叫智

image-20211204101310115

383. 赎金信

难度简单213

为了不在赎金信中暴露字迹,从杂志上搜索各个需要的字母,组成单词来表达意思。

给你一个赎金信 (ransomNote) 字符串和一个杂志(magazine)字符串,判断 ransomNote 能不能由 magazines 里面的字符构成。

如果可以构成,返回 true ;否则返回 false

magazine 中的每个字符只能在 ransomNote 中使用一次。

示例 1:

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

示例 2:

扫描二维码关注公众号,回复: 14382567 查看本文章
输入:ransomNote = "aa", magazine = "ab"
输出:false

示例 3:

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

提示:

  • 1 <= ransomNote.length, magazine.length <= 105
  • ransomNotemagazine 由小写英文字母组成
    //    字符统计
    public boolean canConstruct1(String ransomNote, String magazine) {
    
    
        // 杂志的字符串长度必须大于赎金信
        if (magazine.length() < ransomNote.length()) {
    
    
            return false;
        }
        // 先统计杂志的字符(众所周知英文字母有26个)
        int[] word = new int[26];
        for (int i = 0; i < magazine.length(); i++) {
    
    
            // a=97
            word[magazine.charAt(i) - 'a']++;
        }
        // 判断赎金信的字符
        for (int i = 0; i < ransomNote.length(); i++) {
    
    
            word[ransomNote.charAt(i) - 'a']--;
            if (word[ransomNote.charAt(i) - 'a'] < 0) {
    
    
                return false;
            }
        }
        return true;
    }
 //    字符统计优化
    public boolean canConstruct2(String ransomNote, String magazine) {
    
    
        if (ransomNote.length() > magazine.length()) {
    
    
            return false;
        }
        int[] cnt = new int[26];
        for (char c : magazine.toCharArray()) {
    
    
            cnt[c - 'a']++;
        }
        for (char c : ransomNote.toCharArray()) {
    
    
            cnt[c - 'a']--;
            if (cnt[c - 'a'] < 0) {
    
    
                return false;
            }
        }
        return true;
    }

本人csdn博客:https://blog.csdn.net/weixin_46654114

转载说明:跟我说明,务必注明来源,附带本人博客连接。

猜你喜欢

转载自blog.csdn.net/weixin_46654114/article/details/123011673