Creating a recursive method for Palindrome

前端 未结 21 1975
野的像风
野的像风 2020-12-03 06:28

I am trying to create a Palindrome program using recursion within Java but I am stuck, this is what I have so far:

 public static void main (String[] args){
         


        
21条回答
  •  半阙折子戏
    2020-12-03 06:50

    public static boolean isPalindrome(String p)
        {
            if(p.length() == 0 || p.length() == 1)
                // if length =0 OR 1 then it is
                return true; 
    
             if(p.substring(0,1).equalsIgnoreCase(p.substring(p.length()-1))) 
                return isPalindrome(p.substring(1, p.length()-1));
    
    
            return false;
        }
    

    This solution is not case sensitive. Hence, for example, if you have the following word : "adinida", then you will get true if you do "Adninida" or "adninida" or "adinidA", which is what we want.

    I like @JigarJoshi answer, but the only problem with his approach is that it will give you false for words which contains caps.

提交回复
热议问题