5. Longest Palindromic Substring

5. Longest Palindromic Substring

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

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"
题意:给出一个字符串,求其最长回文子串
代码如下:
var longestPalindrome = function(s) {
    let max=0,start=0;
    if(s.length<2) return s;
//     从位置i开始到j结束,返回最长的回文子串长度
    let hasPalindrome=function(str,i,j){
        while(i>=0 && j<str.length && str.charAt(i)==str.charAt(j)){
            i--;
            j++;
        }
        if(max<j-i-1){
            start=i+1;
            max=j-i-1;
        }
    }
//     区分奇偶回文
    for(let i=0;i<s.length;i++){
        hasPalindrome(s,i,i);
        hasPalindrome(s,i,i+1);
    }
    return s.substring(start,start+max);
};

 

上一篇:Python pyQt4/PyQt5 学习笔记4(事件和信号)


下一篇:可搜索的wooyun镜像网站