第50题 Longest Palindromic Substring

本文介绍了一种使用Java实现的高效算法,用于查找给定字符串中的最长回文子串。该方法通过动态规划的方式检查所有可能的子串,判断其是否为回文,并记录最长的回文子串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

Hide Tags
  String




Solution in Java:
public class Solution {
    public String longestPalindrome(String s) {
        int len = s.length();
        if(len<2) return s;
        boolean[][] opj = new boolean[len][len];
        //opj[i][j] denotes if s[i...j] is a palindromic, so we have i<=j and opj[m][m]=true(0<=m<len)
        
        for(int m=0; m<len; m++) opj[m][m] = true;
        int max = 0, start = 0;
        
        for(int j=1; j<len; j++){
            for(int i=0; i<j; i++){ 
                if(s.charAt(i)==s.charAt(j)){
                    //special cases:
                    //j>i, so j-i>0. for j-i=1, opj[i][j]=true for s[i]=s[j]
                    //               for j-i=2, i+1=j-1, so opj[i][j]=opj[i+1][j-1]=true
                    if(i+1>j-1)     opj[i][j] = true; 
                    else            opj[i][j] = opj[i+1][j-1];
                    if(opj[i][j]&&j-i+1>max){
                        max = j-i+1;
                        start = i;
                    }
                }
                else opj[i][j] = false; //s[i]!=s[j] then opj[i][j] = false
            }
        }
        
        return s.substring(start, start+max);   
        //Note that shoud be substring(start, start+max), not substring(start, max) 
        //in Java, substring(startIndex, endIndex), the second parameter is the end position 
        //(not include the last character in substring), 
        //so that endIndex-startIndex is the length of substring, which is max in this case.
        
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值