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
一刷
题解:给了一个magazine字符串,判断这个字符串里面所有的字符能不能组成ransom note string
方法:有一个长度为26的统计magazine中 character frequency的array, 然后对ransom中的字符遍历,如果存在,frequency--, 如果有frequency<0, 不能构成ransom, return false
public class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] arr = new int[26];
//count the character frequency
for (int i = 0; i < magazine.length(); i++) {
arr[magazine.charAt(i) - 'a']++;
}
for (int i = 0; i < ransomNote.length(); i++) {
if(--arr[ransomNote.charAt(i)-'a'] < 0) {
return false;
}
}
return true;
}
}
二刷
同上,频率数组
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] mag = new int[26];
for(int i=0; i<magazine.length(); i++){
mag[magazine.charAt(i) - 'a']++;
}
for(int i=0; i<ransomNote.length(); i++){
if(--mag[ransomNote.charAt(i) - 'a']<0) return false;
}
return true;
}
}