最长回文串

此博客链接:https://www.cnblogs.com/ping2yingshi/p/14347689.html

最长回文串

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

题目

给你一个字符串 s,找到 s 中最长的回文子串。

示例 1:

输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。
示例 2:

输入:s = "cbbd"
输出:"bb"
示例 3:

输入:s = "a"
输出:"a"
示例 4:

输入:s = "ac"
输出:"a"

题解

 利用动态规划,先给所有的回文串标识为false,当确定为回文数时,标识为true,然后判断回文字符串最大的是哪个。

代码

class Solution {
    public String longestPalindrome(String s) {
    int len=s.length();
    if(len==1)
    {
        return s;
    }
    String result=s.charAt(0)+"";
    boolean [][] bool=new boolean[len][len];
    for(int i=0;i<len;i++)
    {
        bool[i][i]=true;
    }
    for(int i=len-1;i>=0;i--)
    {
        for(int j=i+1;j<len;j++)
        {
            if(s.charAt(i)==s.charAt(j))
            {
                if(j-i==1)
                   {
                       bool[i][j]=true;
                   }
                   else
                   {
                       bool[i][j]=bool[i+1][j-1];
                   }
            }
            else{
                bool[i][j]=false;
            }
            if(bool[i][j]==true)
            {
                 String temp=s.substring(i,j);
                 if(result.length()<temp.length())
                 {
                     result=temp;
                 }
            }
        }
    }
    return result;
    }
}

正确代码

和上面错误代码比较,substring函数的第一个参数是开始下标,但是结束时,不包括结束下标的的字母,所以在写结束字符下标时,需要加1。

class Solution {
    public String longestPalindrome(String s) {
    int len=s.length();
    if(len==1)
    {
        return s;
    }
    String result=s.charAt(0)+"";
    boolean [][] bool=new boolean[len][len];
    for(int i=0;i<len;i++)
    {
        bool[i][i]=true;
    }
    for(int i=len-1;i>=0;i--)
    {
        for(int j=i+1;j<len;j++)
        {
            if(s.charAt(i)==s.charAt(j))
            {
                if(j-i==1)
                   {
                       bool[i][j]=true;
                   }
                   else
                   {
                       bool[i][j]=bool[i+1][j-1];
                   }
            }
            else{
                bool[i][j]=false;
            }
            if(bool[i][j]==true)
            {
                 String temp=s.substring(i,j+1);
                 if(result.length()<temp.length())
                 {
                     result=temp;
                 }
            }
        }
    }
    return result;
    }
}

结果

 

 正确结果

出来混总是要还的
原文地址:https://www.cnblogs.com/ping2yingshi/p/14347689.html