文章 224
评论 6
浏览 200766
String - 383. Ransom Note

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;
    }
}

标题:String - 383. Ransom Note
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/06/28/1561652244835.html

Nothing just happens, it's all part of a plan.

取消