我写了以下功能
//O(n^2)
void MostCommonPair(char * cArr , char * ch1 , char * ch2 , int * amount)
{
int count , max = 0;
char cCurrent , cCurrent2;
int i = 0 , j;
while(*(cArr + i + 1) != '\0')
{
cCurrent = *(cArr + i);
cCurrent2 = *(cArr + i + 1);
for(j = i , count = 0 ; *(cArr + j + 1) != '\0' ; j++)
{
if(cCurrent == *(cArr + j) && cCurrent2 == *(cArr + j + 1))
{
count++;
}
}
if(count > max)
{
*ch1 = cCurrent;
*ch2 = cCurrent2;
max = *amount = count;
}
i++;
}
}
对于以下输入
“xdshahaalohalobscxbsbsbs”
ch1 = b ch2 = s 数量 = 4
但在我看来,这个函数效率很低,有没有办法只通过一次字符串或将运行大小减少到 O(n)?