String - 383. Ransom Note

时间:2022-07-25
本文章向大家介绍String - 383. Ransom Note,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

383. Ransom Note

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note.

Note: You may assume that both strings contain only lowercase letters.

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

思路:

采用一个数组,来记录magazines字符串每一位字母是否出现过,然后再去ransom比对,就可以得出结果。

代码:

java:

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