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)。 同时请,关注我们的公众号,获取最新关于专知以及人工智能的资讯、技术、算法等内容。扫一扫下方关注我们的微信公众号。