5. Longest Palindromic Substring最大回文子串
阅读原文时间:2023年07月10日阅读:1
int sta = 0;  
int max = 1;  
public String longestPalindrome(String s) {  
    /\*  
    判断回文有两种:  
        1.最大回文子序列求长度:  
            用动态规划,dp\[sta\]\[end\] 代表开头为sta、结尾为end的部分最大回文子序列的长度是多少  
            dp\[sta\]\[end\] = (s.charAt(sta)==s.charAt(end))?dp\[sta+1\]\[end-1\]+2:max(dp\[sta\]\[end-1\],dp\[sta+1\]\[end\])  

        2.最大回文子串:  
            用两遍延伸法,分为两种情况,奇数子串和偶数子串:  
            把所有字符当做中轴,遍历一遍,每当长度超过,就更新结果  
     \*/  
    int l = s.length();  
    if (l==0)  
        return "";  
    for (int i = 0; i < l; i++) {  
        //奇数情况  
        helper(s,i,i);  
        //偶数情况  
        helper(s,i,i+1);  
    }  
    //这里注意是前闭后开区间,注意区间  
    return s.substring(sta,sta+max);  
}  
public void helper(String s,int left,int right){  
    //从中轴向两边延伸,注意最后的结果多了一次  
    while (left >= 0&& right < s.length()&& s.charAt(left)==s.charAt(right))  
    {  
        left--;  
        right++;  
    }  
    //由于left多减了一次,right多加了一次,所以处理要注意  
    if (max < right-left-1)  
    {  
        max = right-left-1;  
        sta = left+1;  
    }  
}

最大回文子序列在:http://www.cnblogs.com/stAr-1/p/7444994.html

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章