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
|
class Solution { public int longestPalindromeSubseq(String s) {
char[] arr = s.toCharArray(); int res = 0; int leftRes = 0; int rightRes = 0;
for (int i = 0; i < arr.length; i++) { leftRes = plalindrome(arr, i, i); rightRes = plalindrome(arr, i, i+1); if(leftRes>res) res = leftRes; if(rightRes>res) res = rightRes; }
return res; }
public int plalindrome(char[] arr, int left, int right){
if(left<0 || right>arr.length-1) return 0; if(arr[left] == arr[right]){ if(left==right) return plalindrome(arr, left-1, right+1) +1; else return plalindrome(arr, left-1, right+1) +2; } else { return Math.max(plalindrome(arr, left-1, right), plalindrome(arr, left, right+1)); } } }
|