【LeeCode】383. Ransom letter

Give you two strings: ransomNote and magazine, determine whether ransomNote can be represented by < a consists of the characters inside i=4>. magazine

Whether it is possible, return true; no return false.

magazineEach character in can be used only once in ransomNote.

Example 1:

Input: ransomNote = "a", magazine = "b"
Output: false

Example 2:

Input: ransomNote = "aa", magazine = "ab"
Output: false

Example 3:

Input: ransomNote = "aa", magazine = "aab"
Output: true

hint:

  • 1 <= ransomNote.length, magazine.length <= 105

  • ransomNote and magazine consist of lowercase English letters

Solution [Use an array of length 26 to record the number of times letters appear in magazine. Then use ransomNote to verify whether this array contains all the letters required by ransomNote]:

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

Guess you like

Origin blog.csdn.net/weixin_48144018/article/details/134889282