I am solving Leetcode problem #125 for checking if a stripped version of input string is a palindrome. What I mean by stripped is a string extracted from the original string and the extracted/stripped string contains only [a-z][0-9]
When the code under #0 is changed to #1, the program crashes with the error message. However when I replace it to #1 as shown below, the code gets accepted.
// https://leetcode.com/problems/valid-palindrome/
// Leetcode-125
// Helperfunction to find if a palindrome
bool isPal(char *s , int count)
{
int iterations = (count/2)-1;
for (int i = 0; i <= iterations; i++)
{
if (s[i] != s[count-1-i])
{
return false;
}
}
return true;
}
// function that Leetcode's main calls.
bool isPalindrome(char * s)
{
int i = 0, j=0;
int count = 0;
if (!s)
return false;
// Count number of valid characters. Replace invalid characters with 0xff.
// Change Upper to lower case numbers
while (s[i] != '\0')
{
// [a-z][0-9]
if ((s[i] >= '0' && s[i] <='9') ||
(s[i] >= 'a' && s[i] <='z'))
{
count++;
}
else
{
if ((s[i] >= 'A' && s[i] <='Z'))
{
count++;
s[i] = s[i] + ('a' - 'A');
}
else
{
s[i] = 0xff;
}
}
i++;
}
if (!count)
return true;
char *stripped = (char *) malloc ((count+1) * sizeof(char));
i = 0;
#if 0
// Enabling this causes a crash
while(s[i] != '\0')
{
if(s[i] != 0xff)
{
stripped[j] = s[i];
j++;
}
i++;
}
#else
while(s[i] != '\0')
{
if ((s[i] >= '0' && s[i] <='9') ||
(s[i] >= 'a' && s[i] <='z'))
{
stripped[j] = s[i];
j++;
}
i++;
}
#endif
stripped[count] = '\0';
return isPal(stripped, count);
}
