Longest Palindromic Substring
Given a string S,find the longest palindromic substring in S.
Sample Input 1 : abaxabaxabb
Sample Output 1 : baxabaxab
Sample Input 2 : babad
Sample Output 2 : bab (aba also correct)
Sample Input 3 : baad
Sample Output 3 : aa
Sample Input 1 : abaxabaxabb
Sample Output 1 : baxabaxab
Sample Input 2 : babad
Sample Output 2 : bab (aba also correct)
Sample Input 3 : baad
Sample Output 3 : aa
#include <stdio.h> #include<string.h> int main() { char str[50],tmp[50],pal[50]; int len3=0,len2=0,a=0,len,i,j,k,front,back,count=0; gets(str); len=strlen(str); //palindromic substring of length 3 or more for(i=1;i<len;i++) { front=i+1; back=i-1; a=0; while(back>=0 && front<len) { if(str[front]==str[back]) { a=0; for(k=back;k<=front;k++) { tmp[a]=str[k]; a++; } len2=strlen(tmp); front++; back--; } else{ break; } } if(len2>len3) { strcpy(pal,tmp); len3=len2; count++; // check whether palindromic substring length is 3 or more } } //palindromic substring of length 2 if(count==0) { for(i=0;i<len;i++) { if(str[i]==str[i+1]) { printf("%c%c",str[i],str[i+1]); break; } } } else { puts(pal); } return 0; }
OUTPUT :
0 comments