我试图编写一个算法来查找字符串的字母表子串的数量。例如,字符串"abba"
有4:
(1)"a"
,"a"
(2)"b"
,"b"
(3)"ab"
,"ba"
(4)"abb"
,"bba"
我试图用来优化的事实是
如果一个字符串没有长度为k的字符串子串, 那么它没有长度为k + 1
的字形对子串
你能否确认这是否真实?
因为我的算法
static int NumAnagrammaticalPairs(string str)
{
int count = 0; // count of anagrammatical pairs found
int n = str.Length / 2; // OPTIMIZATION: only need to look through the substrings of half the size or less
for(int k = 1; k <= n; ++k)
{
// get all substrings of length k
var subsk = GetSubstrings(str,k).ToList();
// count the number of anagrammatical pairs
var indices = Enumerable.Range(0, subsk.Count);
int anapairs = (from i in indices
from j in indices
where i < j && IsAnagrammaticalPair(subsk[i], subsk[j])
select 1).Count();
// OPTIMIZATION: if didn't find any anagrammatical pairs in the substrings of length k,
// there are no anagrammatical pairs in the substrings of length k+1, so we can exit
// the loop early
if(anapairs == 0)
break;
else
count += anapairs;
}
return count;
}
将结果 sliggggtttthhhhly 关闭(通常在1之后)测试用例中的实际结果。
答案 0 :(得分:4)
情况并非如此 - abcd
和cdab
是长度为4的字谜,但你找不到长度为3的anagram子串。具体而言,abcdab
不起作用,因为它包含abcd
和cdab
,但没有3个字谜(来自abc
,bcd
,cda
,dab
)。