Creating a recursive method for Palindrome

前端 未结 21 1934
野的像风
野的像风 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:52

    Here I am pasting code for you:

    But, I would strongly suggest you to know how it works,

    from your question , you are totally unreadable.

    Try understanding this code. Read the comments from code

    import java.util.Scanner;
    public class Palindromes
    {
    
        public static boolean isPal(String s)
        {
            if(s.length() == 0 || s.length() == 1)
                // if length =0 OR 1 then it is
                return true; 
            if(s.charAt(0) == s.charAt(s.length()-1))
                // check for first and last char of String:
                // if they are same then do the same thing for a substring
                // with first and last char removed. and carry on this
                // until you string completes or condition fails
                return isPal(s.substring(1, s.length()-1));
    
            // if its not the case than string is not.
            return false;
        }
    
        public static void main(String[]args)
        {
            Scanner sc = new Scanner(System.in);
            System.out.println("type a word to check if its a palindrome or not");
            String x = sc.nextLine();
            if(isPal(x))
                System.out.println(x + " is a palindrome");
            else
                System.out.println(x + " is not a palindrome");
        }
    }
    
    0 讨论(0)
  • 2020-12-03 06:53
    public class chkPalindrome{
    
    public static String isPalindrome(String pal){
    
    if(pal.length() == 1){
    
    return pal;
    }
    else{
    
    String tmp= "";
    
    tmp = tmp + pal.charAt(pal.length()-1)+isPalindrome(pal.substring(0,pal.length()-1));
    
    return tmp;
    }
    
    
    }
         public static void main(String []args){
    
             chkPalindrome hwObj = new chkPalindrome();
             String palind = "MADAM";
    
           String retVal= hwObj.isPalindrome(palind);
          if(retVal.equals(palind))
           System.out.println(palind+" is Palindrome");
           else
           System.out.println(palind+" is Not Palindrome");
         }
    }
    
    0 讨论(0)
  • 2020-12-03 06:54

    Some of the codes are string heavy. Instead of creating substring which creates new object, we can just pass on indexes in recursive calls like below:

    private static boolean isPalindrome(String str, int left, int right) {
        if(left >= right) {
            return true;
        }
        else {
            if(str.charAt(left) == str.charAt(right)) {
    
                return isPalindrome(str, ++left, --right);
            }
            else {
                return false;
            }
        }
    }
    
    
     public static void main(String []args){
        String str = "abcdcbb"; 
        System.out.println(isPalindrome(str, 0, str.length()-1));
     }
    
    0 讨论(0)
  • 2020-12-03 06:55
    String source = "liril";
    StringBuffer sb = new StringBuffer(source);
    String r = sb.reverse().toString();
    if (source.equals(r)) {
        System.out.println("Palindrome ...");
    } else {
        System.out.println("Not a palindrome...");
    }
    
    0 讨论(0)
  • 2020-12-03 06:57

    Well:

    • It's not clear why you've got two methods with the same signature. What are they meant to accomplish?
    • In the first method, why are you testing for testing for a single space or any single character?
    • You might want to consider generalizing your termination condition to "if the length is less than two"
    • Consider how you want to recurse. One option:
      • Check that the first letter is equal to the last letter. If not, return false
      • Now take a substring to effectively remove the first and last letters, and recurse
    • Is this meant to be an exercise in recursion? That's certainly one way of doing it, but it's far from the only way.

    I'm not going to spell it out any more clearly than that for the moment, because I suspect this is homework - indeed some may consider the help above as too much (I'm certainly slightly hesitant myself). If you have any problems with the above hints, update your question to show how far you've got.

    0 讨论(0)
  • 2020-12-03 07:00

    Here are three simple implementations, first the oneliner:

    public static boolean oneLinerPalin(String str){
        return str.equals(new StringBuffer(str).reverse().toString());
    }
    

    This is ofcourse quite slow since it creates a stringbuffer and reverses it, and the whole string is always checked nomatter if it is a palindrome or not, so here is an implementation that only checks the required amount of chars and does it in place, so no extra stringBuffers:

    public static boolean isPalindrome(String str){
    
        if(str.isEmpty()) return true;
    
        int last = str.length() - 1;        
    
        for(int i = 0; i <= last / 2;i++)
            if(str.charAt(i) != str.charAt(last - i))
                return false;
    
        return true;
    }
    

    And recursively:

    public static boolean recursivePalin(String str){
        return check(str, 0, str.length() - 1);
    }
    
    private static boolean check (String str,int start,int stop){
        return stop - start < 2 ||
               str.charAt(start) == str.charAt(stop) &&
               check(str, start + 1, stop - 1);
    }
    
    0 讨论(0)
提交回复
热议问题