美文网首页
5-longest-palindromic-substring

5-longest-palindromic-substring

作者: 本一和他的朋友们 | 来源:发表于2019-03-31 11:52 被阅读0次

    Longest Palindromic Substring

    Given a strings, find the longest palindromic substring ins. You may assume that the maximum length ofsis 1000.
    Example 1:

    *Input:* “babad”
    *Output:* “bab”
    *Note:* “aba” is also a valid answer.
    

    Example 2:

    *Input:* “cbbd”
    *Output:* “bb”
    

    solution:

    function longestPalinDrome(s) {
      function expandAroundCneter(left, right) {
        while (left >= 0 && right < s.length && s[left] === s[right]) {
          left--;
          right++;
        }
        return s.slice(left + 1, right);
      }
      if (!s) {
        return "";
      }
      let longest = s[0];
    
      for (var i = 0; i < s.length; i++) {
        let odd = expandAroundCneter(i, i);
        if (odd.length > longest.length) {
          longest = odd;
        }
    
        let even = expandAroundCneter(i, i + 1);
        if (longest.length < even.length) {
          longest = even;
        }
      }
      return longest;
    }
    

    相关文章

      网友评论

          本文标题:5-longest-palindromic-substring

          本文链接:https://www.haomeiwen.com/subject/lbmybqtx.html