Saturday 20 June 2015

Finding the largest palindrome in a string

This cpp code finds the starting location of the largest palindrome in a string and also finds that string.

// finding the largest palindrome in a string
#include<iostream>
#include<cstring>
#include<conio.h>

using namespace std;
int main()
{
    char string[]="hxkahssjaisjaiomadamjaisjais"; // taking string to check
    int start=0;                                                         // start marker
    int end=0;                                                          // end marker
    int i;                                                      
    int left;                                                              // left of the starting position i.e i
    int right;                                                           // right of the starting position i.e i
    int c;
    int maxsize=0;                                                 /* getting the max size of the
    int loc=0;                                                              palindrome string */
    for(i=0;i<strlen(string)-1;i++)                        // staring from the index i and looping
    {
        left=i;
        right=i;
        c=0;
        while(left>0)
        {
        if(string[left--]!=string[right++])               // checking the condition of failure
        {
            break;
        }
        c++;                                                           // incrementing when true
    }
        if(c>maxsize)                                           // checking for the new maxsize
    {
        maxsize=c;                                              // new maxsize
        loc=i;                                                       // new location
    }
    }
    start=loc-maxsize;                                       // start of the palindrome    
    end=loc+maxsize;                                       // end of the palindrome
    cout<<"The length of the maximum sized palindrome is"<<maxsize<<endl;
    cout<<"The location of the maximum sized palindrome is"<<(start+2)<<endl;
    for(int j=start+1;j<end;j++)
    {
        cout<<string[j];
    }
    getch();
    return 0;
}

No comments:

Post a Comment