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".
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
bool compare(int* sCnt, int* pCnt, int size) {
for (int i = 0; i < size; i++) {
if (sCnt[i] != pCnt[i]) return false;
}
return true;
}
int* findAnagrams(char* s, char* p, int* returnSize) {
int sLen = strlen(s);
int pLen = strlen(p);
int* res = (int*) malloc(sLen * sizeof(int));
*returnSize = 0;
if (sLen < pLen) return res;
int pCnt[26];
int sCnt[26];
memset(pCnt, 0, 26 * sizeof(int));
memset(sCnt, 0, 26 * sizeof(int));
for (int i = 0; i < pLen; i++) {
pCnt[p[i] - 'a']++;
}
for (int i = 0; i < pLen; i++) {
sCnt[s[i] - 'a']++;
}
if (true == compare(sCnt, pCnt, 26)) {
res[*returnSize] = 0;
*returnSize += 1;
}
for (int i = pLen; i < sLen; i++) {
sCnt[s[i - pLen] - 'a']--;
sCnt[s[i] - 'a']++;
if (true == compare(sCnt, pCnt, 26)) {
res[*returnSize] = i - pLen + 1;
*returnSize += 1;
}
}
return res;
}
438. Find All Anagrams in a String
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 文章源地址 算法介绍: 第一步 NumberOfDeference = p.length(),用来表示目前窗口中的...
- 题目的通过率越来越低,题目越来越长,题意不好理解,边界问题,优化问题叠加,导致解题时间大大增加,对我的目标--快速...
- Given a string s and a non-empty string p, find all the s...
- Given a stringsand anon-emptystringp, find all the start ...