对称子字符串的最大长度

题目:输入一个字符串,输出该字符串中对称的子字符串的最大长度。
比如输入字符串“google”,由于该字符串里最长的对称子字符串是“goog”,因此输出4


方法:

1. 值得注意的是,回文的2种形式,aba, abba;

1.对于aba的形式, 从字符串中的每一个位置i,像两边扩展一位如果a[i-1]=a[i+1],那么继续扩展,直到a[i-k]!=a[i+k]或者i-k,i+k超出了数组的边界。 

2. 对于与abba形式,从第一个b开始,首先判断a[i] == a[i+1]是否为真,然后从i-1,i+1+1开始分别向两边扩展,直到a[i-k] != a[i+1+k]或者i-k,i+k+1超出了数组的边界。

3. 总结一下,对于每一个位置i,向两边扩展的时候都要考虑上面2种情况。

[cpp]  view plain copy
  1. #include<iostream>  
  2. using namespace std;  
  3.    
  4. void display(char *str,int from,int to)//输出from和to位置之间的字符串  
  5. {  
  6.     while(from<=to)  
  7.      {  
  8.                    cout<<*(str+from);  
  9.                    from++;  
  10.      }  
  11.     cout<<endl;  
  12. }  
  13. int fun(char *str)  
  14. {  
  15.     if(str ==NULL)  
  16.            return0;  
  17.     int len =strlen(str);  
  18.     if(len ==1)  
  19.           return 1;  
  20.     int i=0;  
  21.     int max =1;  
  22.    while(i<len-1)  
  23.     {  
  24.             if(str[i] == str[i+1]) //判断是否是abba类型的回文  
  25.              {  
  26.                        int k=1;  
  27.                        while((i-k)>=0&& (i+1+k)<len && str[i-k]==str[i+1+k])  
  28.                                       k++;  
  29.                        k--;  
  30.                       cout<<i<<" even: ";  
  31.                        display(str,i-k,i+1+k);  
  32.                        int lena =  2*k;  
  33.                        max = lena>max?lena:max;  
  34.              }  
  35.              //判断是否是aba类型的回文  
  36.                        int k=1;  
  37.                        while((i-k)>=0&& (i+k)<(len-1) && str[i-k]==str[i+k])  
  38.                                       k++;  
  39.                        k--;  
  40.                        cout<<i<<" odd:";  
  41.                        display(str,i-k,i+k);  
  42.                        int lena = 2*k+1;  
  43.                        max =lena>max?lena:max;  
  44.                         
  45.                 
  46.             i++;   
  47.     }  
  48.     returnmax;  
  49. }  
  50. int main()  
  51. {  
  52.     char*str="daaccacdaaaddf";  
  53.    cout<<fun(str)<<endl;  
  54.     getchar();  
  55.     return 0;  
  56. }  

你可能感兴趣的:(Google,null,扩展)