【LeetCode 438】关关的刷题日记37 Find All Anagrams in a String

时间:2022-05-07
本文章向大家介绍【LeetCode 438】关关的刷题日记37 Find All Anagrams in a String,主要内容包括题目、思路、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

关关的刷题日记37 – Leetcode 438. Find All Anagrams in a String

题目

Given 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 s and 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]

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".

题目的意思是要求找出s中所有p的相同字母异序词的起始索引。

思路

思路:刷题日记36——Leetcode 242. Valid Anagram中是判断是否是相同字母异序词。知道了如何判断相同字母异序词之后,这个题目让我们找出s中所有的p的相同字母异序词索引,于是采用滑动窗口的思想:遍历s,判断每一个字符开始的p.size()个字符是否是p的相同字母异序词即可。

class Solution {public:
    vector<int> findAnagrams(string s, string p) {
        vector<int>m(26,0);
        vector<int>temp(26,0);
        vector<int>re;
        for(char x:p)
        {
            m[x-'a']++;
        }
        for(int i=0; i<s.size(); i++)
        {
            temp=m;
            if(temp[s[i]-'a']!=0 && i+p.size()<=s.size())
            {
                for(int k=i; k<i+p.size();k++)
                    temp[s[k]-'a']--;
                int flag=1;
                for(int x:temp)
                {
                    if(x!=0)
                    {
                        flag=0;
                        break;
                    }
                }
                if(flag)
                    re.push_back(i);
                else
                    flag=1;
            }
        }
        return re;
    }};

人生易老,唯有陪伴最长情,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)。