难度:Easy
给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。 字符串只包含小写英文字母,并且字符串 s 和 p 的长度都不超过 20100。
说明: 字母异位词指字母相同,但排列不同的字符串。 不考虑答案输出的顺序。
示例 1:
输入:
s: "cbaebabacd" p: "abc"
输出:
[0, 6]
解释:
起始索引等于 0 的子串是 "cba", 它是 "abc" 的字母异位词。
起始索引等于 6 的子串是 "bac", 它是 "abc" 的字母异位词。
示例 2:
输入:
s: "abab" p: "ab"
输出:
[0, 1, 2]
解释:
起始索引等于 0 的子串是 "ab", 它是 "ab" 的字母异位词。
起始索引等于 1 的子串是 "ba", 它是 "ab" 的字母异位词。
起始索引等于 2 的子串是 "ab", 它是 "ab" 的字母异位词。
方法:
- 最原始的比较法: Hash table按序比较,时间复杂度O(nm),提交超时。
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
vector<int> res;
if(s==p) return res;
if(s.length()<p.length()) return res;
int len=p.size();
unordered_map<char,int>b1;
for(auto i:p)
b1[i]++;
for(int i=0;i<s.length()-len+1;i++)
{
unordered_map<char,int>a1;
int flag=0;
for(int j=i;j<i+len;j++)
{
a1[s[j]]++;
}
for(int j=i;j<i+len;j++)
{
if(a1[s[j]]!=b1[s[j]])
{
flag=1;
break;
}
}
if(!flag)
res.push_back(i);
}
return res;
}
};
- 优化: Hash table+ slide window. 时间复杂度O(n)
lass Solution {
public:
vector<int> findAnagrams(string s, string p) {
vector<int> res;
vector<int>sv(26,0);
vector<int>pv(26,0);
int len=p.length();
for(auto c: p)
++pv[c-'a'];
for(int i=0;i<s.length();i++)
{
if(i>=len) --sv[s[i-len]-'a'];
++sv[s[i]-'a'];
if(sv == pv) res.push_back(i-len+1);
}
return res;
}
};