package com.thinkjava.ly2011dell;
/**
* 对称子字符串的最长长度
* @author ly
*
*/
public class MaxSymmetricalSubStr {
public static void main(String[] args) {
char[] in = {'g','o','e','o','g','l','e'};//求这个源字符串的 最长对称子串 的长度
System.out.println(getMaxSymSubStr(in));
}
/**
* 对每个元素分别判断以自己为中心的,以自己及自己+1位置元素为中心 的对称串的最长长度
* O(n2)
* @param in
* @return
*/
public static int getMaxSymSubStr(char[] in){
int max = 0;
int[] a = new int[in.length];
int[] b = new int[in.length];
///n次循环
for(int i = 0;i<in.length;i++){
每次循环内部以自己为中心向两端延伸 + 以自己和自己下一个为中心向两端延伸 大概 耗费O(n)
//以自己为中心
a[i] = 1;
int left = i-1;
int right = i+1;
for(;left>=0 && right<in.length;left--,right++){
if(in[left]==in[right])
a[i]+=2;
else
break;
}
//以自己和自己下一个为中心
left = i;
right= i+1;
for(;left>=0 && right<in.length;left--,right++){
if(in[left]==in[right])
b[i]+=2;
else
break;
}
if(a[i]>max) max = a[i];
if(b[i]>max) max = b[i];
}
return max;
}
}