383. 赎金信
给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。
如果可以,返回 true ;否则返回 false 。
magazine 中的每个字符只能在 ransomNote 中使用一次。
示例 1:
输入:ransomNote = "a", magazine = "b"
输出:false
示例 2:
输入:ransomNote = "aa", magazine = "ab"
输出:false
示例 3:
输入:ransomNote = "aa", magazine = "aab"
输出:true
package priv20240531.solution338; public class Solution { public boolean canConstruct(String ransomNote, String magazine) { //把字符转化成ASCII值进行计算 int[] count_char = new int[26]; // 资源字符 for (char c : magazine.toCharArray()) { count_char[c - 'a']++; } //消耗字符 for (char c : ransomNote.toCharArray()) { count_char[c - 'a']--; if (count_char[c - 'a'] < 0) {return false;} } return true; } }