leetcode(java) 5. Longest Palindromic Substring

文章介绍了一种利用动态规划算法来找出给定字符串中的最长回文子串的方法。通过二维布尔数组记录子串是否为回文,从单字符开始逐步扩展到更长子串,最终找到最长的回文子串。提供的Java代码示例展示了具体的实现过程。

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

Q: Given a string s, return the longest palindromic substring in s.

Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.

A: I have two solution.

Solution1 :

I will use dynamic programming to solve this problem.

Two demension array f[i] [j] represents whether the substring s[i...j] is palindromic.

transfer equation:

        when i==j, f[i][i] = true;

        when i!=j, f[i][j] = (s[i]==s[j]) && f[i+1][j-1] ? true: false;

In order to claculate all the substring, I calculate the substring from length 1 to length n.

Otherwise, it can not calculate the array correctly.

public String longestPalindrome(String s) {
        int n = s.length();
        String res = s.substring(0,1);
        if(s.length()<2){
            return s;
        }
        boolean[][] f = new boolean[n][n];
        for(int i=0;i<n;i++){
            f[i][i] = true;
        }

        for(int i=0;i<n-1;i++){
            if( s.charAt(i)==s.charAt(i+1)){
                f[i][i+1] = true;
                if(res.length()<2){
                    res = s.substring(i,i+2);
                }
            }
        }

        for(int l=2;l<n;l++){
            for(int i=0;i<n && i+l<n;i++){
                int j = i+l;
                if(s.charAt(i)==s.charAt(j)){
                    f[i][j] = f[i+1][j-1];
                    if(f[i][j] && (j-i+1)>res.length()){
                        res = s.substring(i,j+1);
                    }
                }
            }
        }
        return res;
    }

Solution 2:

I will firstly determine the number of middle element.

There are two possibilities: one or two (a, or aa)

Then I wil loop the whole String and judge whether it is a palindromic.

class Solution {
    public String longestPalindrome(String s) {
        int n = s.length();
        if(n < 2){
            return s;
        }
        String res = s.substring(0,1);
        for(int i=0;i<n;i++){
            String ans = judge(i,i,s);
            if(ans.length()>res.length()){
                res = ans;
            }
        }

        for(int i=0;i<n-1;i++){
            if(s.charAt(i)!=s.charAt(i+1)) continue;
            String ans = judge(i,i+1,s);
            if(ans.length()>res.length()){
                res = ans;
            }
        }

        return res;
    }   

    public String judge(int begin, int end, String s){
        int n = s.length();
        while(begin>=0 && end<n && s.charAt(begin)==s.charAt(end)){
            begin--;
            end++;
        }
        return s.substring(begin+1, end);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值