题解 | 最长回文子串

最长回文子串

https://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int result=0;
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String input=in.nextLine();
            if(input!=null&&input.length()>0){
                result=getLongestPalindrome(input).length();
                System.out.println(result);
            }
            
        }
    }

    //中心扩展法获取回文子串的长度
    private static int expandAroundCenter(String s,int left,int right){
        while(left>=0&&right<s.length()&&s.charAt(left)==s.charAt(right)){
            left--;
            right++;
        }
        return right-left-1;

    }
    //中心扩展法获取最长的回文子串
    public static String  getLongestPalindrome(String str){
        int start=0;
        int end=0;
        int len=0;
        String  result=null;
       
        for(int i=0;i<str.length();i++){
            //奇数回文子串
           int m=expandAroundCenter(str,i,i);
            //偶数回文子串
           int n=expandAroundCenter(str,i,i+1);
           len=Math.max(m,n);
           if(len>end-start){
            start=i-(len-1)/2;
            end=i+len/2;
           }
        }
        result=str.substring(start,end+1);
        return result;
    }
}

全部评论

相关推荐

03-31 14:46
已编辑
门头沟学院 Web前端
励志成为双港第一ja...:这其实很正常,离的太远了,他认为你不会来,就为了混个面试,而且成本很高,实习生都优先选本地高校。吃了地域的亏,所有很多时候地域可能比院校层次更重要。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务