The details of the problem are as the same as described in title. The time complexity and space complexity can be ignored in the specific question.
I did not stumble upon questions involving palindromes in my studies, so I am not at all sure about my solution. I am here in search of an enlightenment.
Thanks for reading.
I tried to approach it as a backtracking question. Basically, a palindrome like abba, has 2 identical 'a', along with 2 identical 'b',
so, I just thought that I should "drill inside" the phrase and check if each outer shell is identical:
a b c c b a
first shell - a a
second shell - b b
third shell - c c
you get my terminology.
I just: defined two pointers, one at the start of the array (left) and one in the end of the array (right).
And thought of 3 cases:
- both pointers are moving together towards each other
- the left pointer only is moving
- the right pointer only is moving
if one of the shells are not two equal characters, we know this certain word, can't be a palindrome.
like "abca" is not a palindrome, because b is different than c in the "second shell". and I am not sure if this is the way to go.
Here is the code:
Public static int longestPalindrome (int[]arr)
{
return longestPalindrome(arr, 0, arr.length-1, 0);
}
Private static int longestPalindrome (int[]arr, int leftPointer, int rightPointer, int palinLength)
{
/* if the left and right number are not the same, a palindrome in this length can not be
Valid */
if(leftPointer < 0 || rightPointer < 0 || leftPointer>arr.length-1 || rightPointer>arr.length-1)
{
return 0;
}
if(arr[leftPointer] != arr[rightPointer])
{
return palinLength;
}
if(arr[leftPointer] == arr[rightPointer])
{
return palinLength+1;
}
return max(longestPalindrome(arr, leftPointer+1, rightPointer, palinLength),
longestPalindrome(arr, leftPointer, rightPointer-1, palinLength),
longestPalindrome(arr, leftPointer+1, rightPointer-1, palinLength));
}
/* a helper method to find the max out of the three cases */
private static int max(int a, int b, int c)
{
int biggest = Integer.MIN_VALUE;
if(a > biggest)
{
biggest = a;
}
if(b > biggest)
{
biggest = b;
}
if(c > biggest)
{
biggest = c;
}
return biggest;
}