Skip to content

Instantly share code, notes, and snippets.

@zry656565
Created April 4, 2016 07:22
Show Gist options
  • Save zry656565/a18c0ebaf8a66b04eb6767ae212370ab to your computer and use it in GitHub Desktop.
Save zry656565/a18c0ebaf8a66b04eb6767ae212370ab to your computer and use it in GitHub Desktop.
Longest Palindromic Subsequence
/**
* @param {string} s
* @return {int}
*/
var longestPalindromeLength = function(s) { 'use strict'
let n = s.length;
if (n <= 1) return n;
let L = {
arr: [],
get(i, j) {
if (j < i) return 0;
else if (j === i) return 1;
else return this.arr[j][i];
},
set(i, j, val) {
this.arr[j] = this.arr[j] || [];
this.arr[j][i] = val;
}
};
for (let d = 1; d < n; d++) {
for (let i = 0; i < n-d; i++) {
let j = i + d;
let result;
if (s[i] === s[j]) result = L.get(i+1, j-1) + 2;
else result = Math.max(L.get(i+1, j), L.get(i, j-1));
L.set(i, j, result);
}
}
return L.get(0, n-1);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment