Я просматривал код KMP, когда заметил Longest Prefix, который также является частью вычисления суффикса KMP.Вот как это происходит,
void computeLPSArray(char* pat, int M, int* lps)
{
int len = 0;
lps[0] = 0;
int i = 1;
while (i < M) {
if (pat[i] == pat[len]) {
len++;
lps[i] = len;
i++;
}
else
{
if (len != 0) {
len = lps[len - 1]; //<----I am referring to this part
}
else
{
lps[i] = 0;
i++;
}
}
}
}
Теперь часть, в которой я запутался, была та, которую я показал в комментариях в приведенном выше коде.Теперь мы знаем, что когда код содержит цикл, подобный следующему
int a[m];
memset(a, 0, sizeof(a));
for(int i = 0; i<m; i++){
for(int j = i; j>=0; j--){
a[j] = a[j]*2;//This inner loop is causing the same cells in the 1
//dimensional array to be visited more than once.
}
}
Сложность получается O (m * m).Точно так же, если мы запишем вышеупомянутое вычисление LPS в следующем формате
while(i<M){
if{....}
else{
if(len != 0){
//doesn't this part cause the code to again go back a few elements
//in the LPS array the same way as the inner loop in my above
//written nested for loop does? Shouldn't that mean the same cell
//in the array is getting visited more than once and hence the
//complexity should increase to O(M^2)?
}
}
}
Может случиться так, что способ, которым я думаю, что сложность вычислена, неправильный.Поэтому, пожалуйста, уточните.