找出字符串中对称的子字符串的最大长度(最长回文)

 

背景:

所谓对称子字符串,就是这个子字符串要么是以其中一个词对称:比如 “aba”, “abcba”;要么就完全对称:比如"abba", "abccba"。

问题:

给你一个字符串,找出该字符串中对称的子字符串的最大长度。

思路:

首先,我们用字符数组 char[] array 来保持这个字符串,假设现在已经遍历到第 i 个字符,要找出以该字符为“中心”的最长对称字符串,我们需要用另两个指针分别向前和向后移动,直到指针到达字符串两端或者两个指针所指的字符不相等。因为对称子字符串有两种情况,所以需要写出两种情况下的代码:

1. 第 i 个字符是该对称字符串的真正的中心,也就是说该对称字符串以第 i 个字符对称, 比如: “aba”。代码里用 index 来代表 i.

2. 第 i 个字符串是对称字符串的其中一个中心。比如“abba”。

 1 public class Test {
 2 
 3     /**
 4      * @param args
 5      */
 6     public static void main(String[] args) {
 7         // TODO Auto-generated method stub
 8         Test t = new Test();
 9         Item item = t.getLenForSym("sadsaklfjsaldfassafdlas");
10         System.out.println(item.str + " " + item.len);
11     }
12 
13     Item getLenForSym(String s) {
14 
15         Item item = new Item();
16         if (s != null && !s.equals("")) {
17             for (int i = 0; i < s.length(); i++) {
18                 Item item1 = getLenForABCBA(s, i);
19                 if (item1.len > item.len) {
20                     item = item1;
21                 }
22                 Item item2 = getLenForABCCBA(s, i);
23                 if (item2.len > item.len) {
24                     item = item2;
25                 }
26             }
27         }
28 
29         return item;
30     }
31 
32     final static public class Item {
33         int len;
34         String str;
35     }
36 
37     /***
38      * 对于ABCBA 这种情况求长度
39      * 
40      * @param s
41      * @param idx
42      * @return
43      */
44     Item getLenForABCBA(String s, int idx) {
45 
46         int i = 0;
47         int start = 0;
48         int end = 0;
49         for (; i < s.length(); i++) {
50             start = idx - i;
51             end = idx + i;
52             if (start >= 0 && end < s.length()
53                     && s.charAt(start) == s.charAt(end)) {
54             } else {
55                 break;
56             }
57         }
58 
59         Item item = new Item();
60         item.str = s.substring(start + 1, end);
61         item.len = 1 + i * 2;
62         return item;
63 
64     }
65 
66     Item getLenForABCCBA(String s, int idx) {
67         int start = 0;
68         int end = 0;
69         int i = 0;
70         for (; i < s.length(); i++) {
71             start = idx - i;
72             end = idx + 1 + i;
73             if (start >= 0 && end < s.length()
74                     && s.charAt(start) == s.charAt(end)) {
75             } else {
76                 break;
77             }
78         }
79 
80         Item item = new Item();
81         item.str = s.substring(start + 1, end);
82         item.len = item.str.length();
83 
84         return item;
85 
86     }
87 }
原文地址:https://www.cnblogs.com/wjw334/p/string.html