Creating a recursive method for Palindrome

2019-01-11 11:45发布

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){
 System.out.println(isPalindrome("noon"));
 System.out.println(isPalindrome("Madam I'm Adam"));
 System.out.println(isPalindrome("A man, a plan, a canal, Panama"));
 System.out.println(isPalindrome("A Toyota"));
 System.out.println(isPalindrome("Not a Palindrome"));
 System.out.println(isPalindrome("asdfghfdsa"));
}

public static boolean isPalindrome(String in){
 if(in.equals(" ") || in.length() == 1 ) return true;
 in= in.toUpperCase();
 if(Character.isLetter(in.charAt(0))
}

public static boolean isPalindromeHelper(String in){
 if(in.equals("") || in.length()==1){
  return true;
  }
 }
}

Can anyone supply a solution to my problem?

21条回答
做自己的国王
2楼-- · 2019-01-11 12:32

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));
 }
查看更多
女痞
3楼-- · 2019-01-11 12:33

Here is my go at it:

public class Test {

    public static boolean isPalindrome(String s) {
        return s.length() <= 1 ||
            (s.charAt(0) == s.charAt(s.length() - 1) &&
             isPalindrome(s.substring(1, s.length() - 1)));
    }


    public static boolean isPalindromeForgiving(String s) {
        return isPalindrome(s.toLowerCase().replaceAll("[\\s\\pP]", ""));
    }


    public static void main(String[] args) {

        // True (odd length)
        System.out.println(isPalindrome("asdfghgfdsa"));

        // True (even length)
        System.out.println(isPalindrome("asdfggfdsa"));

        // False
        System.out.println(isPalindrome("not palindrome"));

        // True (but very forgiving :)
        System.out.println(isPalindromeForgiving("madam I'm Adam"));
    }
}
查看更多
戒情不戒烟
4楼-- · 2019-01-11 12:33

Simple Solution 2 Scenario --(Odd or Even length String)

Base condition& Algo recursive(ch, i, j)

  1. i==j //even len

  2. if i< j recurve call (ch, i +1,j-1)

  3. else return ch[i] ==ch[j]// Extra base condition for old length

public class HelloWorld {


 static boolean ispalindrome(char ch[], int i, int j) {
  if (i == j) return true;

  if (i < j) {
   if (ch[i] != ch[j])
    return false;
   else
    return ispalindrome(ch, i + 1, j - 1);
  }
  if (ch[i] != ch[j])
   return false;
  else
   return true;

 }
 public static void main(String[] args) {
  System.out.println(ispalindrome("jatin".toCharArray(), 0, 4));
  System.out.println(ispalindrome("nitin".toCharArray(), 0, 4));
  System.out.println(ispalindrome("jatinn".toCharArray(), 0, 5));
  System.out.println(ispalindrome("nittin".toCharArray(), 0, 5));

 }
}
查看更多
▲ chillily
5楼-- · 2019-01-11 12:39
public static boolean isPalindrome(String in){
   if(in.equals(" ") || in.length() < 2 ) return true;
   if(in.charAt(0).equalsIgnoreCase(in.charAt(in.length-1))
      return isPalindrome(in.substring(1,in.length-2));
   else
      return false;
 }

Maybe you need something like this. Not tested, I'm not sure about string indexes, but it's a start point.

查看更多
对你真心纯属浪费
6楼-- · 2019-01-11 12:40

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");
    }
}
查看更多
劳资没心,怎么记你
7楼-- · 2019-01-11 12:40

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.

查看更多
登录 后发表回答