最短SNIPPETS变形吧,一样2指针2字典,O(n)扫过去
public bool IsAnagramSubString(string str, string anagram)
{
var pStart = 0;
var pEnd = 0;
var targetDict = anagram.GroupBy(p => p)
.ToDictionary(
g => g.Key,
g => g.Count()
);
var targetTotalNum = targetDict.Values.Sum();
var foundDict = targetDict.ToDictionary(p => p.Key, p => 0);
var foundTotalNum = 0;
while (pEnd < str.Length)
{
var c = str[pEnd];
if (!targetDict.ContainsKey(c))
{
foundTotalNum = 0;
foundDict = targetDict.ToDictionary(p => p.Key, p => 0);
}
else
{
foundDict[str[pEnd]]++;
foundTotalNum++;
while (foundDict[c] > targetDict[c])
{
foundDict[str[pStart]]--;
foundTotalNum--;
pStart++;
}
}
pEnd++;
if (foundTotalNum == targetTotalNum) return true;
}
return false;
}