// C# implementation of the approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to return the count
// of distinct palindromic sub-strings
// of the given string s
static int palindromeSubStrs(String s)
{
// To store the positions of
// palindromic sub-strings
int[,] dp = new int[s.Length, s.Length];
int st, end, i, len;
// Map to store the sub-strings
Dictionary<String,
Boolean> m = new Dictionary<String,
Boolean>();
for (i = 0; i < s.Length; i++)
{
// Sub-strings of length 1 are palindromes
dp[i,i] = 1;
// Store continuous palindromic sub-strings
if(!m.ContainsKey(s.Substring(i, 1)))
m.Add(s.Substring(i, 1), true);
}
// Store palindromes of size 2
for (i = 0; i < s.Length - 1; i++)
{
if (s[i] == s[i + 1])
{
dp[i, i + 1] = 1;
if(!m.ContainsKey(s.Substring(i, 2)))
m.Add(s.Substring(i, 2), true);
}
// If str[i...(i+1)] is not a palindromic
// then set dp[i,i + 1] = 0
else
dp[i, i + 1] = 0;
}
// Find palindromic sub-strings of length>=3
for (len = 3; len <= s.Length; len++)
{
for (st = 0; st <= s.Length - len; st++)
{
// End of palindromic substring
end = st + len - 1;
// If s[start] == s[end] and
// dp[start+1,end-1] is already palindrome
// then s[start....end] is also a palindrome
if (s[st] == s[end] &&
dp[st + 1, end - 1] == 1)
{
// Set dp[start,end] = 1
dp[st, end] = 1;
m.Add(s.Substring(st, end + 1-st), true);
}
// Not a palindrome
else
dp[st, end] = 0;
}
}
// Return the count of distinct palindromes
return m.Count;
}
// Driver Code
public static void Main(String[] args)
{
String s = "abaaa";
Console.WriteLine(palindromeSubStrs(s));
}
}
// This code is contributed by PrinciRaj1992