老卫带你学---leetcode刷题(438. 找到字符串中所有字母异位词)

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

问题:

给定两个字符串 s 和 p,找到 s 中所有 p 的 异位词 的子串,返回这些子串的起始索引。不考虑答案输出的顺序。

异位词 指由相同字母重排列形成的字符串(包括相同的字符串)。

bash 复制代码
示例 1:

输入: s = "cbaebabacd", p = "abc"
输出: [0,6]
解释:
起始索引等于 0 的子串是 "cba", 它是 "abc" 的异位词。
起始索引等于 6 的子串是 "bac", 它是 "abc" 的异位词。
bash 复制代码
 示例 2:

输入: s = "abab", p = "ab"
输出: [0,1,2]
解释:
起始索引等于 0 的子串是 "ab", 它是 "ab" 的异位词。
起始索引等于 1 的子串是 "ba", 它是 "ab" 的异位词。
起始索引等于 2 的子串是 "ab", 它是 "ab" 的异位词。
bash 复制代码
提示:

1 <= s.length, p.length <= 3 * 104
s 和 p 仅包含小写字母

解决:

直接count字符计数,然后直接比对

python 复制代码
class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        n,m,res=len(s),len(p),[]
        if n<m:return res
        p_cnt=[0]*26
        s_cnt=[0]*26
        for i in range(m):
            p_cnt[ord(p[i])-ord('a')]+=1
            s_cnt[ord(s[i])-ord('a')]+=1
            
        if s_cnt==p_cnt:
            res.append(0)
            
        for i in range(m,n):
            s_cnt[ord(s[i-m])-ord('a')]-=1 ##每次从count中去掉旧字母
            s_cnt[ord(s[i])-ord('a')]+=1 ##每次给count中增加新字母
            if s_cnt==p_cnt: 
                res.append(i-m+1) ## 记得i-m+1
        return res
相关推荐
alphaTao8 小时前
LeetCode 每日一题 2026/7/27-2026/8/2
python·算法·leetcode
Hi李耶14 小时前
【LeetCode】9-回文数
算法·leetcode·职场和发展
海绵天哥18 小时前
LeetCode Hot 100 | 链表(下)· 分组翻转与设计(C++ 题解)
c++·leetcode·链表
tkevinjd1 天前
力扣131-分割回文串
算法·leetcode·深度优先
zander2582 天前
LeetCode 78. 子集
算法·leetcode·深度优先
Tisfy2 天前
LeetCode 3014.输入单词需要的最少按键次数 I:遍历 / if-else计算(比纯数学公式写起来麻烦但好想)
数学·算法·leetcode·字符串·题解·贪心
tkevinjd2 天前
力扣239-滑动窗口最大值
算法·leetcode·职场和发展
圣保罗的大教堂2 天前
leetcode 628. 三个数的最大乘积 简单
leetcode
良木林2 天前
矩阵 - LeetCode hot 100
线性代数·算法·leetcode·矩阵
兰令水2 天前
hot100【查缺补漏+打印线程abc】【2026.7.30打卡-java版本】
java·算法·leetcode