/** * @param {string} s * @return {string} */ var longestPalindrome = function(s) { if (s.length === 1) return s; let dp = [...newArray(s.length)].map(e =>newArray(s.length).fill(false)); for (let i = 0; i < s.length; i++) { dp[i][i] = true; }

let start = 0; let end = 0; for (let j = 1; j < s.length; j++) { for (let i = 0; i < j; i++) { // Note the `j - i < 3` here. We need to check it in case `i+1 > j-1` or `i+1 = j-1`. if (s[i] === s[j] && (j - i < 3 || dp[i+1][j-1])) { dp[i][j] = true; if (j - i > end - start) { start = i; end = j; } } } } return s.substring(start, end + 1); };