兩種遞迴方式實現迴文字

mxdxm8899發表於2010-04-30

條件:迴文字為奇數長度

第一種:

import java.util.*;
public class rollback {

    static Vector s;
    public static void main(String[] args)
    {
        rollback a =new rollback();
        s = new Vector();
        String v="123454321";
        for(int i=0;i<v.length();i++)
        {
            s.add(v.charAt(i));
        }
        System.out.println(a.fun(s,0,8,8));
    }


    boolean fun(Vector s,int start,int end,int n)
    {
           if(start==end)
               return true;
           if(s.get(start)==s.get(end))
               return fun(s,start+1,n-start-1,n);

             return false;
    }
}

 

第二種:

import java.util.*;
public class rollback1 { 

    static Vector s; 
    public static void main(String[] args) 
    { 
        rollback1 a =new rollback1(); 
        char[] number = new char[]{'a','b','c','d','c','b','a'}; 
        System.out.println(String.valueOf(fun(number))); 
    }

    static boolean fun(char[] number) 
    { 
        if(number.length%2 == 0) 
            return false; 
        if(number.length== 1) 
            return true; 
        else 
        { 
            if(number[0] != number[number.length - 1]) 
                return false; 
            else 
            { 
                //delete the first element and the last element 
                char[] numberCopy = new char[number.length - 2]; 
                for(int i = 0; i < number.length -2; i ++) 
                    numberCopy[i] = number[i + 1]; 
                
                   return fun(numberCopy); 
            } 
        } 
    } 
} 

 

相關文章