"No one is harder on a talented person than the person themselves" - Linda Wilkinson ; "Trust your guts and don't follow the herd" ; "Validate direction not destination" ;

April 10, 2014

Interview Question - Maximum Palindrome Substring in given String

Some candidates write logic, working code, impressive ideas. This question 'Maximum Palindrome Substring in given String' I got a good answer during one of interview discussions.

I tried the same in codepad link. This is C++ code. The solution code is

int main()
{
    char inputname[50] = "aaabbaa";
    char match[50];
    char temp[50];
    char revtemp[50];
    int length = 0;
    int currentpalindromelength = 0;
    int maxpalindromelength = 0;
    int palstart=0, palend=0;
    int i,j;
    for(i = 0;inputname[i] !='\0'; i++)
    {
        length++;
    }
    printf("length is %d\n", length);
    for(int ipos = 0; ipos  < length; ipos++)
    {
        for(j = ipos+1; j < length; j++)
        {
            int startpos=0;
            for(int k = ipos; k < j; k++)
            {
                temp[startpos++] = inputname[k];
            }
            temp[startpos] = '\0';
            printf("string to compare %s \n", temp);
            startpos=0;
            for(int z = j-1; z >=0; z--)
            {
                revtemp[startpos++] = inputname[z];
            }
            revtemp[startpos] = '\0';
            printf("reverse string to compare %s\n", revtemp);
            int result = strcmp(temp, revtemp);
            if (result == 0)
            {
                    printf("Both strings are equal \n");
                    currentpalindromelength = 0;
                    for(int iCur = 0;temp[iCur] !='\0'; iCur++)
                    {
                        currentpalindromelength ++;
                    }
                    if(currentpalindromelength > maxpalindromelength)
                    {
                        maxpalindromelength = currentpalindromelength;
                        palstart = ipos;
                        palend =j;
                    }
            }
            else
            {
                  printf("\nBoth strings are not equal \n");
           }
        }
    }
    printf("max palindrome length is %d",maxpalindromelength);
    printf("start pos is %d\n",palstart);
    printf("end pos is %d\n",palend);
    for(int k = palstart; k < palend; k++)
    {
         printf("%c",inputname[k]);
    }
    printf("\n");
    return 0;
}


This worked for multiple cases. codepad is very good!.

Happy Coding!!!

No comments: