题目(easy)
给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。
如果可以,返回 true ;否则返回 false 。
magazine 中的每个字符只能在 ransomNote 中使用一次。
思路
用长度为 26 的数组记录次数。
之所以不用 Map,是因为 Map 要维护红黑树、哈希表,要做哈希函数,是更加费时的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const canConstruct = (ransomNote, magazine) => { const strArr = new Array(26).fill(0); let base = 'a'.charCodeAt(); for(const s of magazine) { strArr[s.charCodeAt() - base]++; } for(const s of ransomNote) { const index = s.charCodeAt() - base; if (!strArr[index]) { return false; } strArr[index]--; } return true; }
|
时间复杂度: O(n)。
空间复杂度: O(1)。