LeetCode 438. Find All Anagrams in a String. Tags: 滑动窗口sliding window,hash table

该篇博客介绍了如何利用滑动窗口和哈希表来查找一个字符串`s`中所有与目标字符串`p`相同字母组成的子串(即回文子串)。首先,博主定义了一个`Solution`类,并实现了一个`findAnagrams`函数,该函数接受两个字符串`s`和`p`作为参数。函数中,博主首先检查`s`的长度是否大于`p`,如果小于则返回空结果。接着,博主用哈希表记录`p`中每个字符的出现次数,然后通过一个滑动窗口遍历`s`,在每次窗口移动时更新哈希表,并判断当前窗口是否与`p`的字符分布相同,若相同则将起始索引加入结果数组。最后返回结果数组。示例中展示了对于不同输入,函数如何找出所有符合条件的子串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:

力扣

Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

Input: s = "cbaebabacd", p = "abc"
Output: [0,6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".
Example 2:

Input: s = "abab", p = "ab"
Output: [0,1,2]
Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".
 

Constraints:

1 <= s.length, p.length <= 3 * 104
s and p consist of lowercase English letters.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-anagrams-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

我的解答:


#include<bits/stdc++.h>
using namespace std;


class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        vector<int> result;

        int lenS = s.length();
        int lenP = p.length();
        if(lenS < lenP) return result;
        // sliding window, 哈希表。统计字符串s的滑动窗口里的各字符出现次数
        vector<int> window(26, 0);

        // 统计字符串p各个字符出现的次数
        vector<int> pCount(26, 0);

        for(int i = 0; i < lenP; i ++){
            window[s[i] - 'a'] ++;
            pCount[p[i] - 'a'] ++;
        }

        // 滑动窗口的左右索引
        int left = 0;
        int right = lenP - 1;
        for(; right < lenS; right ++, left++){
            if(isAnagram(window, pCount)){
                result.push_back(left);
            }
            window[s[left] - 'a'] --;
            if(right + 1 < lenS){
                // 小心right + 1,字符串索引访问越界
                window[s[right + 1] - 'a'] ++;
            }
            
        }

        return result;
    }

    bool isAnagram(vector<int>& window, vector<int>& pCount){
        for(int i = 0; i < 26; i ++){
            if(window[i] != pCount[i]) return false;
        }
        return true;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值