zoukankan      html  css  js  c++  java
  • [leetCode]383.赎金信

    csdn:https://blog.csdn.net/renweiyi1487/article/details/109259360

    给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false。

    (题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。杂志字符串中的每个字符只能在赎金信字符串中使用一次。)

    注意:

    你可以假设两个字符串均只含有小写字母。

    canConstruct("a", "b") -> false
    canConstruct("aa", "ab") -> false
    canConstruct("aa", "aab") -> true

    哈希

    使用数组作为hash表统计“杂志中每个字符的出现次数”,然后遍历“赎金信”中的字符,在哈希表中相应的字符数减一,如果当前字符对应的字符数小于0,则说明“杂志”中的字符不够用了所以返回false,否则返回true

    class Solution {
        public boolean canConstruct(String ransomNote, String magazine) {
            int[] couner2 = new int[26];
            for (char c : magazine.toCharArray()) {
                couner2[c - 'a']++;
            }
            for (char c : ransomNote.toCharArray()) {
                couner2[c - 'a']--;
                if (couner2[c-'a'] < 0)
                    return false;
            }
            return true;
        }
    }
    
  • 相关阅读:
    拥有最多糖果的孩子
    求1+2+…+n
    网络-中间代理
    Header中的Referer属性表示
    ios13.4post请求出现网错错误 network err
    10.8&10.10
    9.23&9.27
    9.16&9.19
    校内模拟赛划水报告(9.9,9.11)
    男人八题 划水题解
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13869467.html
Copyright © 2011-2022 走看看