Map:
function isAnagram(s: string, t: string): boolean {
if (s.length !== t.length) {
return false
}
const count = new Map<string, number>()
for (const char of s) {
count.set(char, (count.get(char) ?? 0) + 1)
}
for (const char of t) {
const current = count.get(char)
if (!current) {
return false
}
count.set(char, current - 1)
}
return true
}26 长度数组:
function isAnagram(s: string, t: string): boolean {
if (s.length !== t.length) {
return false
}
const count = new Array<number>(26).fill(0)
for (let i = 0; i < s.length; i++) {
const sIndex = s.charCodeAt(i) - 97
const tIndex = t.charCodeAt(i) - 97
count[sIndex]++
count[tIndex]--
}
return count.every((value) => value === 0)
}方案 | 时间复杂度 | 空间复杂度 | 特点 |
|---|---|---|---|
|
|
| 通用性强 |
26 长度数组 |
|
| ⭐ 本题推荐 |
这里的:
k表示不同字符的数量。
为什么长度 26 的数组可以认为:
O(1)?
因为不管字符串有:
10 个字符
10000 个字符
100 万个字符这个数组永远只有:
26 个位置它不会随着输入规模变大。
因此空间复杂度是:
O(1)