【LeetCode】383. 赎金信 - hashmap/数组

这里写自定义目录标题

  • 2023-8-28 22:54:39

383. 赎金信

2023-8-28 22:54:39

次数 ----> hashmap 和 数组来进行实现。
【LeetCode】383. 赎金信 - hashmap/数组_第1张图片

public class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
    	// num 用于存储小写字母出现的次数
        int[] num = new int[26];
        int index = 0;
        for(int i = 0; i< magazine.length(); i++){
        	// `两个字符串均只含有小写字母` ,我们可以通过ascii码来确定字母在数组的下标
        	// 记录每一个字母出现的次数
            index = magazine.charAt(i) - 'a';
            num[index]++;
        }
        int subIndex = 0;
        for(int i = 0; i < ransomNote.length(); i ++){
        	// 要拿走的字母的位置
            subIndex = ransomNote.charAt(i) -'a';
            // 如果发现拿走了字母后,当前的的个数 是负数了,证明赎金信ransomNote里面有一个字母无法通过杂志magazine来获得
            if(--num[subIndex] < 0){
            	// 直接返回false
                return false;
            }
        }
        // 能够组成一封赎金信,返回true
        return true;
    }
}

你可能感兴趣的:(#,LeetCode,leetcode,算法,职场和发展)