给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。
如果可以,返回 true ;否则返回 false 。
magazine 中的每个字符只能在 ransomNote 中使用一次。
来源:力扣(LeetCode)
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int a[] = new int[26];
int temp;
for(int i = 0;i < magazine.length();i++){
temp = magazine.charAt(i) - 'a';//charAt()方法用来返回指定索引处的字符
a[temp]++;
}
for(int i = 0;i < ransomNote.length();i++){
temp = ransomNote.charAt(i) - 'a';
if(a[temp] > 0){
a[temp] --;
}//查找每一个字符,找到相应位减一
else{
return false;
}//找不到返回false
}
return true;
}
}