String - 383. Ransom Note

95

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