[leetcode]438. Find All Anagrams in a String

本文介绍了一种在长字符串中查找所有与给定短字符串异位词的算法。通过统计字符频率并滑动窗口匹配,高效地定位所有目标子串。适用于字符串长度不大于20,100的情况。

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

iven a string s and a non-empty string p, find all the start indices of p's anagrams in s.

Strings consists of lowercase English letters only and the length of both strings sand p will not be larger than 20,100.

The order of output does not matter.

Example 1:

Input:
s: "cbaebabacd" p: "abc"

Output:
[0, 6]

分析:

给定两个字符串s和p,找出s中所有包含p的异位词的位置,字母异位词是指包含的字母相同但顺序不同。首先统计p中每个字符出现的次数,然后从s的开头开始,每次找p.size()个字符,来验证字符个数是否相同,如果不相同直接break,如果一直都相同,则将起始位置加入结果res中。

class Solution {
public:
    vector<int> findAnagrams(string s, string p) {
        if (s.empty()) 
            return {};
        int len1 = s.size();
        int len2 = p.size();
        vector<int> res;
        vector<int> tmp1(128 , 0);   
        int i = 0;
        for(char c : p)
           tmp1[c]++;
        while(i < len1)
        {
            bool flag = true;
            vector<int> tmp2 = tmp1;
            for(int j = i; j < i + len2; j++)
        {
                
                if(--tmp2[s[j]] < 0)
                {
                    flag = false;
                    break;
            }   
        }
            if(flag)
                res.push_back(i);
            i++; 
        }
        return res;                
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值