383 赎金信
给你两个字符串:ransomNote
和 magazine
,判断 ransomNote
能不能由 magazine
里面的字符构成。
如果可以,返回 true
;否则返回 false
。
magazine
中的每个字符只能在 ransomNote
中使用一次。
示例 1:
输入:ransomNote = "a", magazine = "b" 输出:false
示例 2:
输入:ransomNote = "aa", magazine = "ab" 输出:false
示例 3:
输入:ransomNote = "aa", magazine = "aab" 输出:true
提示:
-
1 <= ransomNote.length, magazine.length <= 105
-
ransomNote
和magazine
由小写英文字母组成
思路
-
思路还是跟刚刚的字母异位词一样,用数组模拟hashmap,先加再减,最后遍历我们的数组,如果数组中存在大于0的,那么就说明
-
a中有b没有的
-
a中有的个数大于b中有的
-
此时返回false,否则为true;
class Solution {
public boolean canConstruct(String ransomNote, String magazine)
{
int[] count = new int[26];
for(char c : ransomNote.toCharArray())
{
count[c-'a']++;
}
for(char c : magazine.toCharArray())
{
count[c-'a']--;
}
for(int i : count)
{
if(i>0)
{
return false;
}
}
return true;
}
}