TreeviewCopyright © aleen42 all right reserved, powered by aleen42

383. 赎金信

https://leetcode-cn.com/problems/ransom-note/

Java

/*
 * @Author: Goog Tech
 * @Date: 2020-08-24 16:26:33
 * @LastEditTime: 2020-08-24 16:26:50
 * @Description: https://leetcode-cn.com/problems/ransom-note/
 * @FilePath: \leetcode-googtech\#383. Ransom Note\Solution.java
 * @WebSite: https://algorithm.show/
 */

class Solution {
    // 用数组代替哈希表
    public boolean canConstruct(String ransomNote, String magazine) {
        // 初始化整型数组
        int[] countR = new int[26];
        int[] countM = new int[26];
        // 存储每个字符对应的数值,其中 c - a 为数组索引,其取值范围为 0 到 25,而值为该字母出现的次数
        for(char c : ransomNote.toCharArray()) countR[c - 'a'] ++;
        for(char c : magazine.toCharArray()) countM[c - 'a'] ++;
        // 遍历数组,逐个判断 countR 中元素出现的次数是否大于 countM
        for(int i = 0; i < 26; i++) {
            if(countR[i] > countM[i]) {
                return false;
            }
        }
        return true;
    }
}

Python

'''
Author: Goog Tech
Date: 2020-08-24 16:26:37
LastEditTime: 2020-08-24 16:28:45
Description: https://leetcode-cn.com/problems/ransom-note/
FilePath: \leetcode-googtech\#383. Ransom Note\Solution.py
WebSite: https://algorithm.show/
'''

class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        # 遍历 ransomNote 中的元素,判断当前元素在 ransomNote 中出现的次数大于 magazine
        for ch in set(ransomNote):
            if ransomNote.count(ch) > magazine.count(ch):
                return False
        return True
Copyright © GoogTech 2021 all right reserved,powered by GitbookLast update time : 2021-09-15 01:55:05

results matching ""

    No results matching ""