题解 | #最长回文子串#
最长回文子串
http://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af
想了很久,之前写过一个通过了19组用例,差点气死。做出来了既高兴又气的要死。核心思想就是先中心判断,再两边判断。假如字符串是acbbcm,比较理想的模型.中心判断:char[1]与char[2]是否相等,如果相等判断char[1]与char[3],由此类推;如果char[1]不等于char[2],那么判断char[0]与char[2]是否相等,如果相等继续比较char[-1]和char[3],直到不相等,或者越界,然后计算临时长度,接着就是进入下一个中心判断,进入下一个中心也是有技巧的,字符串abbbcccd,第一个中心就是bbb,第二个中心就是ccc。博客写的不多,希望多多包含。
public int getLongestPalindrome(String string, int n) {
char[] chars = string.toCharArray();
if (n == 1){
return 1;
}
if (n == 2){
if (chars[0] == chars[1]){
return 2;
}else {
return 0;
}
}
int length = 0;
int temp = 0;
for (int i = 1;i< n-1;){
int j = i+1;
//中心判断
while (chars[i] == chars[j]){
j = j+1;
//当字符串是abbbb类型的时
if (j == n){
if (i == 1){
if (chars[0] == chars[1]) return n;
return n-1;
}
temp = j-i;
if (temp > length){
return temp;
}else {
return length;
}
}
}
//记录位置,方便计算length,这里就不解释了,狗头保命
int m = j;
int k = i;
//两边判断
while (chars[i-1] == chars[j]){
i = i-1;
j = j+1;
if (i == 0 || j == n){
break;
}
}
//最后计算长度
temp = 2*j-k-m;
if (temp > length) length = temp;
//降低时间复杂度
i = m;
}
return length;
}

