-
Notifications
You must be signed in to change notification settings - Fork 0
/
Q1- LongestPalindromicSubstring.cpp
116 lines (93 loc) · 2.72 KB
/
Q1- LongestPalindromicSubstring.cpp
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
//link to the question - https://www.hackerearth.com/practice/algorithms/dynamic-programming/2-dimensional/practice-problems/algorithm/palindromic-sub-string-length/
#include<bits/stdc++.h>
using namespace std;
bool isPrime(int max)
{
if(max==1)
return false;
if(max==2)
return true;
for(int i = 2;i<max;i++)
{
if(max%i==0)
{
return false;
}
}
return true;
}
int main()
{
int t;
cin>>t;
while(t--)
{
string str;
cin>>str;
int n = str.size();
//create a table to store the bool values ( if str[i] till str[j] is a palindrone, then dp[i][j] =true)
bool dp[n][n];
//initialise table to false
for(int i = 0; i<n; i++)
{
for(int j = 0; j<n; j++)
{
dp[i][j] = false;
}
}
//initialise max_length of palindrone as 1
int max=1;
//str[i] till str[i] is always a palindrone(size=1)
for(int i =0;i<n;i++)
{
dp[i][i] = true;
}
//str[i] till str[i+1] is a palindrone of size 2 only when str[i] == str[i+1]
for(int i =0;i<n-1;i++)
{
if(str[i] == str[i+1])
{
dp[i][i+1] = true;
max =2;
}
else
dp[i][i+1] = false;
}
//str[i] till str[j] is a palindrone of size greater than 2 only when the start and the end character is same
//i.e str[i] == str[j] and it was a palindrone till now. i.e str[i+1][j-1]==true
int start, end;
for(int k = 2; k<n; k++)
{
for(int i = 0; i <n-k; i++)
{
int j =i+k;
if(str[i]==str[j] && dp[i+1][j-1]==true)
{
dp[i][j] = true;
if(j-i+1>max)
{
start = i;
end = j;
max = j-i+1;
}
}
else
{
dp[i][j] = false;
}
}
}
//max is the final length of the palindromic string
//substr(start, index) is the palindromic substring
//check if the max-length is a prime number or not
if(isPrime(max))
{
cout<<"PRIME"<<endl;
}
else
{
cout<<"NOT PRIME"<<endl;
}
}
return 0;
}