Skip to content

438. 找到字符串中所有字母异位词 ​

  • 题号:438
  • 来源:LeetCode
  • 难度:中等
  • 标签:滑动窗口 哈希表 字符串
  • 语言:TypeScript · Python
  • 解法:2 个
  • 作者:lmliheng
  • 最近更新:2026-09-29

TypeScript ​

TypeScript · O(n) 时间 · O(1) 空间 · 更新于 2026-09-27

定长窗口滑动,26 位计数数组逐位比较

typescript
/**
 * @difficulty medium
 * @tags 滑动窗口,哈希表,字符串
 * @time O(n)
 * @space O(1)
 * @note 定长窗口滑动,26 位计数数组逐位比较
 * @438. 找到字符串中所有字母异位词
 */
let s = "cbaebabacd"
let p = "abc"
let p_len = p.length
let s_len = s.length
if (s_len < p_len) {
    []
}
let res: number[] = []
let p_arr = new Array(26).fill(0)
let window = new Array(26).fill(0)
const GetWordIndex = (word: string): number => {
    return word.charCodeAt(0) - 97
}
const ArrayCompare = (a: number[], b: number[]): boolean => {
    return JSON.stringify(a) === JSON.stringify(b)
}
// 初始化
for (let i = 0; i < p_len; i++) {
    p_arr[GetWordIndex(p[i])]++
    window[GetWordIndex(s[i])]++
}
if (ArrayCompare(p_arr, window)) { res.push(0) }

for (let i = p_len; i < s_len; i++) {
    // 左边出去的字符 i-p_len
    window[GetWordIndex(s[i - p_len])]--
    // 右边进入的字符 i
    window[GetWordIndex(s[i])]++
    if (ArrayCompare(p_arr, window)) { res.push(i - p_len + 1) }

}

console.log(res)

源码:ts/leetcode/438. 找到字符串中所有字母异位词.ts

Python ​

Python · O(n) 时间 · O(1) 空间 · 更新于 2026-09-29

定长窗口字母计数,与 p 的计数比较

python
"""
@difficulty medium
@tags 滑动窗口,哈希表,字符串
@time O(n)
@space O(1)
@note 定长窗口字母计数,与 p 的计数比较
438. 找到字符串中所有字母异位词

"""
class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
    
        res=[]
        p_len=len(p)
        s_len=len(s)
        if p_len>s_len:
            return []
        win_p=[0]*26
        win=[0]*26
        for i in range(0,p_len):
            win_p[ord(p[i])-97]+=1
            win[ord(s[i])-97]+=1
        if str(win)==str(win_p):
            res.append(0)
        # print(win,win_p,res)
        for i in range(p_len,s_len):
            win[ord(s[i-p_len])-97]-=1
            win[ord(s[i])-97]+=1
            if str(win)==str(win_p):
                res.append(i-p_len+1)
        return res

源码:python/leetcode/hot100/9.py


在 GitHub 上查看题目所在目录:lmliheng/algorithm