老卫带你学---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
相关推荐
旖旎夜光2 天前
LeetCode 493: 翻转对 (归并排序) —— 题解
c++·笔记·学习·算法·leetcode·排序算法
木井巳2 天前
【动态规划: 子序列问题】最长递增子序列的个数
java·算法·leetcode·动态规划·推荐算法
Navigator_Z2 天前
LeetCode //C - 1326. Minimum Number of Taps to Open to Water a Garden
c语言·算法·leetcode
Rain的Java大神之路2 天前
LeetCode 45 跳跃游戏 II:大厂面试官最爱追问的贪心题,我把骨头给你拆干净了
java·后端·leetcode
让我们一起加油好吗4 天前
【算法刷题】LeetCode 力扣 Hot 100 刷题记录
数据结构·c++·算法·leetcode·面试·笔试
Rain的Java大神之路4 天前
LeetCode 42「接雨水」:面试官百出不厌的题,一文讲透从暴力到双指针 O(1)
java·后端·leetcode
Navigator_Z6 天前
LeetCode //C - 1320. Minimum Distance to Type a Word Using Two Fingers
c语言·算法·leetcode
wy_hhxx7 天前
[Leetcode] 滑动窗口
算法·leetcode·滑动窗口
AIgorithmGEEK7 天前
算法·哈希表|从“逐个比”到“按 key 算位置”
数据结构·c++·算法·leetcode·hash
Navigator_Z7 天前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode