static int MaxLength(char str[], int i, int j)   
     {   
         if (i == j)   
         {   
             return 1;   
         }   
         else if (i > j)   
         {   
             return 0;   
         }   
         else  
         {   
             if (str[i] == str[j])   
             {   
                 return 2 + MaxLength(str, i + 1, j - 1);   
             }   
             else  
             {   
                 return max(MaxLength(str, i + 1, j), MaxLength(str, i, j - 1));   
             }   
         }   
     }   
     
 
         
    private static int max(int maxLength, int maxLength2)
    {
        if (maxLength >= maxLength2)
            return maxLength;
        return maxLength2;
    }    public static void main(String[] args)
    {
         char[] str="aa1bb3bb2aa".toCharArray();   
       
            System.out.println(MaxLength(str, 0, str.length - 1));   
           
    }

解决方案 »

  1.   


    if (str[i] == str[j])   
                 {   
                     return 2 + MaxLength(str, i + 1, j - 1);   
                 }   
    这个判断是有问题的,
    比如abca,你就会得到2+MaxLength("abca",1,2)=2
    而实际上应该=0
    要加个判断
    if{str[i] == str[j]&&MaxLength(str, i + 1, j - 1)>0}{
    return 2 + MaxLength(str, i + 1, j - 1);   
    }
    else{
    return max(MaxLength(str, i + 1, j), MaxLength(str, i, j - 1)); 
    }
      

  2.   

    还是有点问题,这样,条件改为if (str[i] == str[j]&&MaxLength(str, i + 1, j - 1)==(j-i-1))//若子串为全回文   
                {   
                 return 2 + MaxLength(str, i + 1, j - 1);   
                }   
                else  
                {   
                 return max(MaxLength(str, i + 1, j), MaxLength(str, i, j - 1));   
                }   这回结果对了