classSolution:deflongestPalindrome(self,s:str) ->str: n =len(s)if n ==0:return"" res = s[0]defextend(i,j,s):while(i >=0and j <len(s)and s[i]== s[j]): i -=1 j +=1return s[i +1:j]for i inrange(n -1): e1 =extend(i, i, s) e2 =extend(i, i +1, s)ifmax(len(e1), len(e2))>len(res): res = e1 iflen(e1)>len(e2)else e2return res
JavaScript Code:
/* * @lc app=leetcode id=5 lang=javascript * * [5] Longest Palindromic Substring *//** * @param{string} s * @return{string} */varlongestPalindrome=function (s) {// babad// tag : dpif (!s ||s.length===0) return"";let res = s[0];constdp= [];// 倒着遍历简化操作, 这么做的原因是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 1elseif (j - i ===1&& s[i] === s[j]) dp[i][j] =true;// specail case 2elseif (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;};
CPP Code:
class Solution {
private:
int expand(string &s, int L, int R) {
while (L >= 0 && R < s.size() && s[L] == s[R]) {
--L;
++R;
}
return R - L - 1;
}
public:
string longestPalindrome(string s) {
if (s.empty()) return s;
int start = 0, maxLen = 0;
for (int i = 0; i < s.size(); ++i) {
int len1 = expand(s, i, i);
int len2 = expand(s, i, i + 1);
int len = max(len1, len2);
if (len > maxLen) {
start = i - (len - 1) / 2;
maxLen = len;
}
}
return s.substr(start, maxLen);
}
};