383. Ransom Note - jiejackyzhang/leetcode-note GitHub Wiki


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

String类题目。

可采用hash map。当然,如果只有小写英文字母,也可以采用固定长度为26的数组来保存数据。

public class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        for(int i = 0; i < magazine.length(); i++) {
            char c = magazine.charAt(i);
            map.put(c, map.containsKey(c) ? map.get(c)+1 : 1);
        }
        for(int i = 0; i < ransomNote.length(); i++) {
            char c = ransomNote.charAt(i);
            if(!map.containsKey(c)) return false;
            int count = map.get(c);
            if(count == 0) return false;
            map.put(c, count-1);
        }
        return true;
    }
}
⚠️ **GitHub.com Fallback** ⚠️