Runtime: 91.13%
Memory: 98.79%
关键词:ASCII
代码:
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] charNums = new int[26];
for (int i=0; i<magazine.length(); i++){
charNums[magazine.charAt(i)-'a']++;
}
for (int i=0; i<ransomNote.length(); i++){
if (charNums[ransomNote.charAt(i) - 'a'] == 0){
return false;
} else {
charNums[ransomNote.charAt(i) - 'a'] --;
}
}
return true;
}
}
测试用例:
Use Example Testcases
经历/可能的改进:
本来用的HashMap,以为已经极限了,但是出来都是50%左右,疑惑地看了一个C++题解。学到可以用ASCII相减的结果来充当数组索引。极大地优化了运行速度和内存占用。
在submition中还有另一套解法,用时0ms,极致的速度享受,代码:
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] count = new int[26];
for (char ransomNoteChar : ransomNote.toCharArray()) {
int index = magazine.indexOf(ransomNoteChar, count[ransomNoteChar - 'a']);
if (index == -1) {
return false;
}
count[ransomNoteChar - 'a'] = index + 1;
}
return true;
}
}
count
数组依然是用ASCII索引,但是其中存的不是该字符的数量,而是该字符上一次出现在magazine
中的位置,这样下一次从这个位置开始找,如果没找到,就返回false。
我也有想这种解法,但是立即否定了,觉得indeOf
会遍历所以耗时应该会很大,没想到居然这么快。