Problem:
Find the length and/or string of the longest palindrome of a string.
The problem appeared as an Interview question in Amazon, Microsoft.
Solution:
One important property of a palindrome is if we remove the first and last characters of it , it would be another palindrome.
So A string S[a..b] will be a palindrome if and only if S[(a+1)…(b-1)] is a palindrome.
We can use DP to solve the problem.
- Keep a 2D array of ARRAY [String.SIZE] [String.SIZE] for keeping the length of palindrome found from the string.
- Each char of the string is 1 length palindrome sub string. So ARRAY[i][i] = 1 , here i=0….String.SIZE
- Now find the length of possible palindrome for 2 char length strings starting from each index of the string S.
- similarly find palindrome for 3,4,…..char length string of the provided String S.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
#include <stdio.h> #include <string.h> #include <string> #include <iostream> using namespace std; int _max(int a,int b) { if(a<=b) return b; return a; } int findPalindrome(string s,int M,int *st,int *ed) { int arr[M][M]; int j; int max_len=1; (*st)=0; (*ed)=0; for(int i=0;i<M;i++) for(int j=0;j<M;j++) arr[i][j]=0; for(int i=0;i<M;i++) { arr[i][i]=1; } for(int len=2;len<=M;len++) { for(int i=0;(i+len-1)<M;i++) { j=i+len-1; if(s[i]==s[j] && len==2) { arr[i][j]=2; if(max_len<arr[i][j]) { max_len = arr[i][j]; (*st)=i; (*ed)=j; } } if(s[i]==s[j] && len>2 && arr[i+1][j-1]!=0) { arr[i][j]=arr[i+1][j-1]+2; if(max_len<arr[i][j]) { max_len = arr[i][j]; (*st)=i; (*ed)=j; } //cout<<s[i]<<s[j]<<" "<<i<<","<<j<<"\n"; } /*if(s[i]!=s[j]) { arr[i][j]=_max(arr[i+1][j],arr[i][j-1]); }*/ } } return max_len;//arr[0][M-1]; } int main() { int t,n,M; string s; scanf("%d",&t); while(t--) { cin>>s; M=s.size(); int st,ed; //cout<< int length = findPalindrome(s,M,&st,&ed);//<<endl; //cout<<length<<"\n"; for(int i=st;i<=ed;i++)cout<<s[i];cout<<endl; } return 0; } |