题目:给你两个字符串: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 由小写英文字母组成
题目来源:力扣(LeetCode)链接
题解:
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
//magazine中的字符只能使用一次,如果magazine长度小于ransomNote的长度,就直接返回false
if (ransomNote.length() > magazine.length()) {
return false;
}
int[] record = new int[26];
for (int i = 0; i < magazine.length(); i++) {
record[magazine.charAt(i) - 'a']++;
}
for (int i = 0; i < ransomNote.length(); i++) {
record[ransomNote.charAt(i) - 'a']--;
if (record[ransomNote.charAt(i) - 'a'] < 0) {
return false;
}
}
return true;
}
}
标签:ransomNote,false,int,length,笔记,record,magazine,383,赎金
From: https://www.cnblogs.com/benben-home/p/17307766.html