-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongest_Palindrome.cpp
More file actions
83 lines (68 loc) · 2.09 KB
/
Longest_Palindrome.cpp
File metadata and controls
83 lines (68 loc) · 2.09 KB
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
// A C++ dynamic programming
// solution for longest palindrome
#include <bits/stdc++.h>
using namespace std;
// Function to print a substring
// str[low..high]
void printSubStr(
string str, int low, int high)
{
for (int i = low; i <= high; ++i)
cout << str[i];
}
// This function prints the longest palindrome substring
// It also returns the length of the longest palindrome
int longestPalSubstr(string str)
{
// get length of input string
int n = str.size();
// table[i][j] will be false if substring...str[i..j] is not palindrome.
// Else table[i][j] will be true
bool table[n][n];
memset(table, 0, sizeof(table));
// All substrings of length 1 are palindromes
int maxLength = 1;
for (int i = 0; i < n; ++i)
table[i][i] = true;
// check for sub-string of length 2
int start = 0;
for (int i = 0; i < n - 1; ++i) {
if (str[i] == str[i + 1]) {
table[i][i + 1] = true;
start = i;
maxLength = 2;
}
}
// Check for lengths greater than 2.
// k is length of substring
for (int k = 3; k <= n; ++k) {
// Fix the starting index
for (int i = 0; i < n - k + 1; ++i) {
// Get the ending index of substring from
// starting index i and length k
int j = i + k - 1;
// checking for sub-string from ith index to
// jth index iff str[i+1] to str[j-1] is a
// palindrome
if (table[i + 1][j - 1] && str[i] == str[j]) {
table[i][j] = true;
if (k > maxLength) {
start = i;
maxLength = k;
}
}
}
}
cout << "Longest palindrome substring is: ";
printSubStr(str, start, start + maxLength - 1);
// return length of LPS
return maxLength;
}
// Driver Code
int main()
{
string str = "forgeeksskeegfor";
cout << "\nLength is: "
<< longestPalSubstr(str);
return 0;
}