Manacher

 

 1 public class T05_02_Manacher {
 2 
 3     public String longestPalindrome(String s) {
 4         /***
 5          * Manacher 返回 字符串长度
 6          *
 7          */
 8         //1.将字符串处理成Manacher字符串
 9 
10         //2.新建数组,记录相应位置的长度值,,,并且记录最右侧边缘,和对应的i
11 
12         //3.遍历字符串。判断此点是否在右侧边缘以内,若在边缘引内,
13 
14         char[] charArray = manacher(s);
15         int[] pArray = new int[charArray.length];
16         int pR = -1;
17         int index = -1;
18         int max = 0;
19         for (int i = 0; i < charArray.length; i++) {
20             pArray[i] = i < pR ? Math.min(pArray[2 * index - i], pR - i) : 1;
21             while (i + pArray[i] < charArray.length && i - pArray[i] >= 0) {
22                 if (charArray[i + pArray[i]] == charArray[i - pArray[i]]) {
23                     pArray[i]++;
24                 } else {
25                     break;
26                 }
27             }
28 
29             if (pArray[i] + i > pR) {
30                 pR = pArray[i] + i;
31                 index = i;
32             }
33             max = Math.max(max, pArray[i]);
34         }
35         int maxIndex = 0;
36         for (int i = 0; i < pArray.length; i++) {
37             if (pArray[i] == max) {
38                 maxIndex = i;
39                 break;
40             }
41         }
42         return s.substring((maxIndex - max + 2) / 2, (maxIndex - max + 2) / 2 + max - 1);
43 
44     }
45 
46     private char[] manacher(String s) {
47         String str = "#";
48         for (int i = 0; i < s.length(); i++) {
49             str += s.charAt(i) + "#";
50         }
51         return str.toCharArray();
52 
53     }
54 }

 

 

 

 

posted @ 2020-03-06 23:59  海绵爱上星  阅读(118)  评论(0编辑  收藏  举报