5. Longest Palindromic Substring(js)

给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

示例 1:

输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
示例 2:

输入: "cbbd"
输出: "bb"

 

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);
};

 出处:https://leetcode-cn.com/problems/longest-palindromic-substring/

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

posted @ 2019-02-13 23:31  mingL  阅读(114)  评论(0编辑  收藏  举报