luzhipeng 797c817 Jun 4, 2019
0 contributors

### Users who have contributed to this file

99 lines (73 sloc) 2.54 KB

## 题目地址

https://leetcode.com/problems/longest-palindromic-substring/description/

## 题目描述

``````Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Output: "bab"
Note: "aba" is also a valid answer.
Example 2:

Input: "cbbd"
Output: "bb"
``````

## 思路

• 如果一个字符串是回文串，那么在它左右分别加上一个相同的字符，那么它一定还是一个回文串
• 如果一个字符串不是回文串，或者在回文串左右分别加不同的字符，得到的一定不是回文串

```if (s[i] === s[j] && dp[i + 1][j - 1]) {
dp[i][j] = true;
}```

base case就是一个字符（轴对称点是本身），或者两个字符（轴对称点是介于两者之间的虚拟点）。

• ”延伸“（extend）

## 代码

```/*
* @lc app=leetcode id=5 lang=javascript
*
* [5] Longest Palindromic Substring
*/
/**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function(s) {
// tag : dp
if (!s || s.length === 0) return "";
let res = s[0];

const dp = [];

// 倒着遍历简化操作， 这么做的原因是dp[i][..]依赖于dp[i + 1][..]
for (let i = s.length - 1; i >= 0; i--) {
dp[i] = [];
for (let j = i; j < s.length; j++) {
if (j - i === 0) dp[i][j] = true;
// specail case 1
else if (j - i === 1 && s[i] === s[j]) dp[i][j] = true;
// specail case 2
else if (s[i] === s[j] && dp[i + 1][j - 1]) {
// state transition
dp[i][j] = true;
}

if (dp[i][j] && j - i + 1 > res.length) {
// update res
res = s.slice(i, j + 1);
}
}
}

return res;
};```

## 相关题目

You can’t perform that action at this time.