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
实现思路:定义两个辅助数组temp1和temp2,用来记录ransomNote和magazine中的各个字母个数,然后检查如果ransomNote有需要使用某个字母m次,则检查magazine中是否存在对应的字母且个数大于等于m。
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int []temp1 = new int[26];
int []temp2 = new int[26];
for(int i=0;i<ransomNote.length();i++){
temp1[ransomNote.charAt(i)-'a']++;
}
for(int i=0;i<magazine.length();i++){
temp2[magazine.charAt(i)-'a']++;
}
for(int i=0;i<26;i++){
if(temp1[i]!=0){
if(temp1[i]>temp2[i])
return false;
}
}
return true;
}
}
实现代码二:使用一个辅助数组也可以
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
boolean ans=true;
int[] marked=new int[256];
char[] c=magazine.toCharArray();
char[] x=ransomNote.toCharArray();
for(int i=0; i<c.length; i++){
marked[c[i]]++;
}
for(int i=0; i<x.length; i++){
if(marked[x[i]]==0){
ans=false;
break;
}
else{
marked[x[i]]--;
}
}
return ans;
}
}