So I have this string "nmmaddammhelloollehdertr"
, if we split the string into x = "nmmaddamm"
and y = "helloollehdertr"
we could find the LPS to be x = "mmaddamm"
and y = "helloolleh"
. We know that this is the biggest palindrome as x
has a length of 8
, and y
has a length of 10
. 10 * 8 = 80
I attempted this problem by using dynamic programming with Longest Palindromic Subsequence, noting that I need to split the string at a pivot point creating two strings with the longest size.
A brute-force approach was to try every single palindrome for each subsequence, and that was my attempt:
using System;
namespace Palindrome
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetLongestPalindrome("nmmaddammhelloollehdertr"));
}
static int GetLongestPalindrome(string s)
{
int longest = 1;
for (int i = 0; i < s.Length; ++i)
longest = Math.Max(longest, GetLongestPalindromeHelper(s.Substring(0, i)) * GetLongestPalindromeHelper(s.Substring(i)));
return longest;
}
static int GetLongestPalindromeHelper(string str)
{
if (str.Length == 0)
return 1;
/*
* For a str = "madeam"
* || 0 | 1 | 2 | 3 | 4 | 5 ||
* _____|| m | a | d | e | a | m ||
* | 0 m || 1 | 1 | 1 | 1 | 1 |_5_||
* | 1 a || 0 | 1 | 1 | 1 |_3_| 3 ||
* | 2 d || 0 | 0 |_1_| 1 | 1 | 1 ||
* | 3 e || 0 | 0 | 0 | 1 | 1 | 1 ||
* | 4 a || 0 | 0 | 0 | 0 | 1 | 1 ||
* | 5 m || 0 | 0 | 0 | 0 | 0 | 1 ||
*
*/
int[,] matrix = new int[str.Length, str.Length];
// i -> row
// j -> column
// windowSize -> the numbers of chars in the window
// each character is a palindrome with a length 1
for (int i = 0; i < str.Length; ++i)
matrix[i, i] = 1;
// we handled windowSize 1, so we start at 2
for (int windowSize = 2; windowSize <= str.Length; ++windowSize)
{
for (int i = 0, j = windowSize - 1; i < str.Length - windowSize + 1; ++i, j = i + windowSize - 1)
{
if (str[i] == str[j])
matrix[i, j] = matrix[i + 1, j - 1] + 2;
else
matrix[i, j] = Math.Max(matrix[i, j - 1], matrix[i + 1, j]);
}
}
return matrix[0, str.Length - 1];
}
}
}
However, I am sure there is a better way to do this, but I do not know how. Any advice? Also, anyone could point out what the complexity of my code is?
Thanks!