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