版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85019565
Title:Ransom Note 383
Difficulty:Easy
原题leetcode地址:https://leetcode.com/problems/ransom-note/
1. 注解见代码中注释
时间复杂度:O(n),三次一层for循环,最长遍历最长字符串。
空间复杂度:O(n),申请256个长度数组。
/**
* 申请一个数组存放字符的个数,magazine出现加加,ransomNote出现减减,最后只要数组中出现小于0的数,则为false,否则为True
* @param ransomNote
* @param magazine
* @return
*/
public static boolean canConstruct(String ransomNote, String magazine) {
if (ransomNote.length() == 0) {
return true;
}
if (magazine.length() == 0) {
return false;
}
int count[] = new int[256];
for (int i = 0; i < magazine.length(); i++) {
count[magazine.charAt(i)]++;
}
for (int i = 0; i < ransomNote.length(); i++) {
count[ransomNote.charAt(i)]--;
}
for (int e : count) {
if (e < 0) {
return false;
}
}
return true;
}