美文网首页
[力扣] 5. 最长回文子串

[力扣] 5. 最长回文子串

作者: Hunsmore | 来源:发表于2020-03-03 21:18 被阅读0次

链接:https://leetcode-cn.com/problems/longest-palindromic-substring

题目

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

示例

示例 1:

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

示例 2:

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

题解

class Solution {
    int max = 0;
    String ms = "";
    String s;
    int N;
    public String longestPalindrome(String s) {
        //遍历数组,依次以某个元素为中心展开判断是否回文
        //注意偶数回文和奇数回文都需要判断
        N = s.length();
        this.s = s;
        for(int i=0;i<N;i++){
            test(i,i);
            test(i,i+1);
        }
        return ms;
    }
    private void test(int l,int r){
        while(l<N && l>=0 && r<N && r>=0 &&
            s.charAt(l)==s.charAt(r)){
            l--;
            r++;
        }
        int len = r-l-1;
        if(len>max){
            max = len;
            ms = s.substring(l+1,r);
        }
    }
}

相关文章

网友评论

      本文标题:[力扣] 5. 最长回文子串

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