欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

5. Longest Palindromic Substring

程序员文章站 2024-03-23 11:36:34
...

题目: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.

public class Solution {
    public String longestPalindrome(String s) {
        if(s.isEmpty())
           return null;
        if(s.length()==1)
           return s;
        int n=s.length();
    //  String rec=s.substring(0,1);
        String max=s.substring(0,1);
        for(int i=0;i<n;i++)
            {
               
                String rec1=helper(s,i,i+1);
                String rec2=helper(s,i,i);
               
            if(!(rec1.length()<max.length()&&rec2.length()<max.length()))
                if(rec1.length()>=rec2.length())
                   max=rec1;
                else
                   max=rec2;
            }
        return max;
    }
   
    public String helper(String s,int begin,int end)
    {
    while(begin>=0&&end<=s.length()-1&&s.charAt(begin)==s.charAt(end))
        {
            begin--;
            end++;
        }
    return s.substring(begin+1,end);
    }
}