-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLPS.cpp
57 lines (55 loc) · 1.3 KB
/
LPS.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
string LPS(string s)
{
int n = s.size();
string palindrome = "";
int** tab = new int*[n];
string res;
string temp;
//Allocating and Initializing Matrix with 0
for (int i = 0; i < n; i++)
tab[i] = new int[n] {0};
bool* indexes = new bool[n] {false};
//filling diagonals
for (int i = 0; i < n; i++)
tab[i][i] = 1;
int i = 0, j = 1, count = 1;
while (count < n-1)
{
if (j == n)
{
count++;
i = 0;
j = count;
}
if (s[i] == s[j])
{
tab[i][j] = tab[i + 1][j - 1] + 2;
if (!indexes[i] && !indexes[j])//if indexes are not selected
{
if (count == 2)//odd length
{
indexes[i] = true;
indexes[i + 1] = true;
indexes[j] = true;
}
else
{
indexes[i] = true;
indexes[j] = true;
}
}
}
else
tab[i][j] = max(tab[i][j - 1], tab[i + 1][j]);
i++;
j++;
}
for (int i = 0; i < n; i++)
{
cout<<indexes[i]<<' ';
if (indexes[i])
res += s[i];
}
cout << '\n';
return res;
}