二刷 08/2022
Version #1 Array as counter map
Time O(M + N)
Space O(1)
Runtime: 5 ms, faster than 74.47% of Java online submissions for Ransom Note.
Memory Usage: 44.8 MB, less than 85.10% of Java online submissions for Ransom Note.
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] count = new int[26];
for (int i = 0; i < magazine.length(); i++) {
count[magazine.charAt(i) - 'a']++;
}
for (int i = 0; i < ransomNote.length(); i++) {
if (--count[ransomNote.charAt(i) - 'a'] < 0) {
return false;
}
}
return true;
}
}
一刷
对于 “” “” 的情况要在最后判断一下61.66 %
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
if (ransomNote == null || magazine == null) return false;
int[] counter = new int[256];
int match = 0;
for (int i = 0; i < ransomNote.length(); i++) {
counter[ransomNote.charAt(i)]++;
match++;
}
for (int j = 0; j < magazine.length(); j++) {
if (counter[magazine.charAt(j)] > 0) {
counter[magazine.charAt(j)]--;
match--;
}
if (match == 0) return true;
}
return match == 0;
}
}
No comments:
Post a Comment