当前位置:网站首页>Leetcode's ransom letter

Leetcode's ransom letter

2020-11-06 01:15:55 codecraft

order

This article mainly records leetcode The ransom letter

subject

 Give a ransom  (ransom)  String and a magazine (magazine) character string , Judge the first string  ransom  Can I have a second string  magazines  The characters inside make up . If it can be constructed , return  true ; Otherwise return to  false.

( Title Description : In order not to reveal the handwriting of the ransom letter , To search magazines for the letters you need , Make up words to express meaning . Each character in the magazine string can only be used once in the ransom letter string .)

 

 Be careful :

 You can assume that both strings contain only lowercase letters .

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

 source : Power button (LeetCode)
 link :https://leetcode-cn.com/problems/ransom-note
 Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

Answer key

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        int[] charCount = new int[26];
        for(char c : magazine.toCharArray()) {
            charCount[c-'a'] += 1;
        }
        for(char c : ransomNote.toCharArray()) {
            charCount[c-'a'] -= 1;
            if (charCount[c-'a'] < 0) {
                return false;
            }
        }
        return true;
    }
}

Summary

Here we maintain an array of character occurrences , And then count it first magazine The number of occurrences of the character , And then I'm going through ransomNote, For each character that appears, the corresponding count is subtracted by one , Once the count is found to be less than 0 Then return to false, Otherwise, it will return after traversing true.

doc

版权声明
本文为[codecraft]所创,转载请带上原文链接,感谢