-
Notifications
You must be signed in to change notification settings - Fork 0
/
Length_of_longest_palindromic_substring(GFG article).cpp
71 lines (60 loc) · 1.45 KB
/
Length_of_longest_palindromic_substring(GFG article).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
// C++ implementation to find the
// length of longest palindromic
// sub-string using Recursion
#include <iostream>
using namespace std;
// Function to find maximum
// of the two variables
int max(int x, int y)
{
return (x > y) ? x : y;
}
// Function to find the longest
// palindromic substring : Recursion
int longestPalindromic(string str,
int i, int j, int count)
{
// Base condition when the start
// index is greater than end index
if (i > j)
return count;
// Base condition when both the
// start and end index are equal
if (i == j)
return (count + 1);
// Condition when corner characters
// are equal in the string
if (str[i] == str[j]) {
// Recursive call to find the
// longest Palindromic string
// by excluding the corner characters
count = longestPalindromic(str, i + 1,
j - 1, count + 2);
return max(count,
max(longestPalindromic(str, i + 1, j, 0),
longestPalindromic(str, i, j - 1, 0)));
}
// Recursive call to find the
// longest Palindromic string
// by including one corner
// character at a time
return max(
longestPalindromic(str, i + 1, j, 0),
longestPalindromic(str, i, j - 1, 0));
}
// Function to find the longest
// palindromic sub-string
int longest_palindromic_substr(string str)
{
// Utility function call
return longestPalindromic(str, 0,
str.length() - 1, 0);
}
// Driver Code
int main()
{
string str = "aaaabbaa";
// Function Call
cout << longest_palindromic_substr(str);
return 0;
}