您的位置:首页 > 其它

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

2013-07-03 11:37 288 查看
背景:

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

问题:

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

思路:

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

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

public static int MaxLength1(char[] array ,int index){

int length=1;

int dif=1;//与index的距离

//下面的判断顺序若array[index-dif]==array[index+dif]在前将会抛出异常,

while((index-dif)>=0 &&(index+dif)<array.length &&array[index-dif]==array[index+dif]){

length+=2;

dif++;

}

return length;

}

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

public static int MaxLength2(char []array ,int index){

int length=0;

int dif=0;//与index的距离

//下面的判断顺序若array[index-dif]==array[index+dif+1]在前将会抛出异常,

while((index-dif)>=0 &&(index+dif+1)<array.length &&array[index-dif]==array[index+dif+1]){

length+=2;

dif++;

}

return length;

}

有了这样两个函数,我们只需要遍历字符串里所有的字符,就可以找出最大长度的对称子字符串了。

public static void main(String args[]){

Scanner sc=new Scanner(System.in);

System.out.print("请输入字符串!");

char[] n;

String a=sc.next();

n=a.toCharArray();//string类型转char

int Maxlength=0;

for(int i=0;i<n.length;i++){

int tempLength=0;

int length1=MaxLength1(n,i);

int length2=MaxLength2(n,i);

tempLength=(length1>length2)?length1:length2;

if (tempLength > Maxlength) {

Maxlength = tempLength;

}

}

System.out.print(Maxlength);

}

因为找出以第 i 个字符为“中心”对称字符串复杂度为 O(N),所以整个算法的复杂度为O(N^2)。

转自:/article/2769992.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐