Leetcode 383 赎金信

题目

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

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

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

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

解题思路

  哈希计数判断即可。

代码
class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        int[] num = new int[26];
        int lengthM = magazine.length(), lengthR = ransomNote.length();
        for (int i = 0; i < lengthM; i++) num[magazine.charAt(i) - 'a']++;
        for (int i = 0; i < lengthR; i++) {
            if (num[ransomNote.charAt(i) - 'a'] == 0) return false;
            else num[ransomNote.charAt(i) - 'a']--;
        }
        return true;
    }
}

你可能感兴趣的:(Leetcode,leetcode,散列表,算法)