Reputation: 25
I am trying to check whether a the string contains palindrome between the given indices. However I am unable to find the bug in my code.
bool isPal(char a[],int i,int j){
for(int k=i;k<(j-i)/2;k++)
if(a[k]!=a[j--])
return 0;
return 1;
}
Upvotes: 1
Views: 259
Reputation: 218088
You modify j
inside the loop, changing also the end condition (which were incorrect anyway), you might use instead:
bool isPal(const char a[],int i,int j){
for (int k = 0; k < (j - i) / 2 ; k++) {
if (a[i + k] != a[j - k]) {
return false;
}
}
return true;
}
Minimal change from your code would be:
bool isPal(char a[], int i, int j)
{
const int mid_index = (j + i) / 2;
for (int k = i; k < mid_index; k++)
if (a[k] != a[j--])
return 0;
return 1;
}
Upvotes: 2
Reputation: 125
for(int k=i;k<(j-i)/2;k++)
You're starting at i and then going up to j-i-1. This is not what you want. Replace i and j with some values and you'll see.
Upvotes: 0
Reputation: 45454
You error was to increment j
as but also assume (in the loop condition) that it remains at its input value. You could use the input variables also as loop variables
bool isPalindrome(const char*a, int i, int j) {
while(i<j)
if(a[i++] != a[j--])
return false;
return true;
}
when setting the correct stop conditions for the loop is straightforward.
Upvotes: 2
Reputation: 373
You are changing the value of j using j--
, which will affect the condition of your for loop k<(j-1)
Upvotes: 4