求最大回文子串(马拉车算法)

这是正常的马拉车算法

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
       Scanner in = new Scanner(System.in);
       while (in.hasNextLine()) {
        String s = in.nextLine();
        System.out.println(manacher(s));   
       }

    }

    public static int manacher(String s) {
        int count =0;//记录最大回文
        StringBuffer sb = new StringBuffer();
        char[] c =s.toCharArray();
        sb.append("#");
        //对字符串进行封装
        for (int i = 0; i < c.length; i++) {
           sb.append(c[i]);
           sb.append("#");
        }
        int[] rad = new int[sb.length()];//记录新字符串以每个字符为中心的最大回文半径
        char[] cl = sb.toString().toCharArray();
        int max=0;//记录已经搜寻到的回文半径能到达右端的最达大值
        int id=0;//记录回文半径能到达最有端的回文字符串的中心
        for (int i = 1; i < cl.length; i++) {
           if (max>i) {
               rad[i]=Math.min(rad[2*id-i], max-i);
           }else {
               rad[i]=1;
           }
           while (i-rad[i]>=0 && i+rad[i]if (i+rad[i]>max) {
               max=i+rad[i];
               id=i;
           }
           count=Math.max(count, rad[i]-1);
        }


        return count;
     }

}

下面这个是我写的算法,运行起来没有上面的效率好,但是重在好理解

import java.util.Scanner;

public class 回文字符串 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String str1 = sc.nextLine();
            MaxHuiwen(str1);
        }



    }
    public static void MaxHuiwen(String s){
        int count  = 0;
        StringBuffer sb = new StringBuffer();
        char[] c = s.toCharArray();
        sb.append("#");
        for (int i = 0; i < c.length; i++) {
            sb.append(c[i]);
            sb.append("#");
        }
        int rad[] = new int[sb.length()];
        char cl[] = sb.toString().toCharArray();
        int max = 0;
        int id = 0;
        for (int i = 1; i < cl.length; i++) {
            rad[i] = 1;
            while(i-rad[i]>=0 && i+rad[i]if(i + rad[i] > max){
                max = i + rad[i];
                id = i;
            }
            count = Math.max(count, max);
        }
        System.out.println(count);
    }
    public static void MaxHuiwen(String str1, String str2){
        int alen = str1.length() + 1;
        int blen = str2.length() + 1;
        int c[][] = new int[alen][blen];
        int max = 0;
        for (int i = 1; i < alen; i++) {
            for (int j = 1 ; j < blen; j++) {
                if(str1.charAt(i - 1) == str2.charAt(j - 1))
                    c[i][j] = c[i - 1][j - 1] + 1;
                else
                    c[i][j] = 0;
                if(c[i][j] > max)
                    max = c[i][j];
            }
        }
        System.out.println(max);
    }

}

你可能感兴趣的:(算法)