为Palindrome创建一个递归方法

我试图在Java中使用递归创建一个Palindrome程序但是我被卡住了,这是我到目前为止所做的:

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; } } } 

谁能为我的问题提供解决方案?

在这里,我为您粘贴代码:

但是,我强烈建议你知道它是如何工作的,

从你的问题来看,你完全不可读。

尝试理解此代码。 阅读代码中的注释

 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"); } } 

好:

  • 目前尚不清楚为什么你有两个具有相同签名的方法。 他们打算完成什么?
  • 在第一种方法中,为什么要测试单个空格任何单个字符的测试?
  • 您可能需要考虑将终止条件概括为“如果长度小于2”
  • 考虑一下你想要如何递归。 一种选择:
    • 检查第一个字母是否等于最后一个字母。 如果没有,则返回false
    • 现在使用子字符串有效地删除第一个和最后一个字母,并递归
  • 这是否意味着在递归中练习? 这当然是一种方式,但它远非唯一的方式。

我现在不会比现在更清楚地拼出来,因为我怀疑这是作业 – 事实上有些人可能认为上面的帮助太多了(我当然有点犹豫不决)。 如果您对上述提示有任何问题,请更新您的问题以显示您的距离。

 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; } 

也许你需要这样的东西。 没有测试,我不确定字符串索引,但它是一个起点。

我认为,递归不是解决这个问题的最佳方法,但我在这里看到的一种递归方式如下所示:

 String str = prepareString(originalString); //make upper case, remove some characters isPalindrome(str); public boolean isPalindrome(String str) { return str.length() == 1 || isPalindrome(str, 0); } private boolean isPalindrome(String str, int i) { if (i > str.length / 2) { return true; } if (!str.charAt(i).equals(str.charAt(str.length() - 1 - i))) { return false; } return isPalindrome(str, i+1); } 

这是我的意思:

 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")); } } 
 public class palin { static boolean isPalin(String s, int i, int j) { boolean b=true; if(s.charAt(i)==s.charAt(j)) { if(i<=j) isPalin(s,(i+1),(j-1)); } else { b=false; } return b; } public static void main() { String s1="madam"; if(isPalin(s1, 0, s1.length()-1)==true) System.out.println(s1+" is palindrome"); else System.out.println(s1+" is not palindrome"); } } 

有些代码很重。 我们可以在递归调用中传递索引,而不是创建创建新对象的子字符串,如下所示:

 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)); } 

这里有三个简单的实现,首先是oneliner:

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

这是非常缓慢的,因为它创建了一个字符串缓冲区并将其反转,如果它是一个回文符号,整个字符串总是被检查,所以这里是一个只检查所需的字符数量并且就位的实现,所以没有额外的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; } 

递归地:

 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); } 
 public static boolean isPalindrome(String str) { int len = str.length(); int i, j; j = len - 1; for (i = 0; i <= (len - 1)/2; i++) { if (str.charAt(i) != str.charAt(j)) return false; j--; } return true; } 

尝试这个:

 package javaapplicationtest; public class Main { public static void main(String[] args) { String source = "mango"; boolean isPalindrome = true; //looping through the string and checking char by char from reverse for(int loop = 0; loop < source.length(); loop++){ if( source.charAt(loop) != source.charAt(source.length()-loop-1)){ isPalindrome = false; break; } } if(isPalindrome == false){ System.out.println("Not a palindrome"); } else System.out.println("Pailndrome"); } } 
 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..."); } 
 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"); } } 

这是一个忽略指定字符的递归方法:

 public static boolean isPal(String rest, String ignore) { int rLen = rest.length(); if (rLen < 2) return true; char first = rest.charAt(0) char last = rest.charAt(rLen-1); boolean skip = ignore.indexOf(first) != -1 || ignore.indexOf(last) != -1; return skip || first == last && isPal(rest.substring(1, rLen-1), ignore); } 

像这样用它:

 isPal("Madam I'm Adam".toLowerCase(), " ,'"); isPal("A man, a plan, a canal, Panama".toLowerCase(), " ,'"); 

在递归方法中包含不区分大小写是没有意义的,因为它只需要执行一次,除非不允许使用.toLowerCase()方法。

没有比这更小的代码:

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

如果你想检查一下:

 public static boolean palindrome(String x){ if(x==null || x.length()==0){ throw new IllegalArgumentException("Not a valid string."); } return (x.charAt(0) == x.charAt(x.length()-1)) && (x.length()<4 || palindrome(x.substring(1, x.length()-1))); } 

哈哈B-]

 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; } 

此解决方案不区分大小写。 因此,例如,如果您有以下单词:“adinida”,那么如果您执行“Adninida”或“adninida”或“adinidA”,这将是我们想要的。

我喜欢@JigarJoshi的答案,但他的方法唯一的问题是它会给你含有大写字母的错误。

回文示例:

 static boolean isPalindrome(String sentence) { /*If the length of the string is 0 or 1(no more string to check), *return true, as the base case. Then compare to see if the first *and last letters are equal, by cutting off the first and last *letters each time the function is recursively called.*/ int length = sentence.length(); if (length >= 1) return true; else { char first = Character.toLowerCase(sentence.charAt(0)); char last = Character.toLowerCase(sentence.charAt(length-1)); if (Character.isLetter(first) && Character.isLetter(last)) { if (first == last) { String shorter = sentence.substring(1, length-1); return isPalindrome(shorter); } else { return false; } } else if (!Character.isLetter(last)) { String shorter = sentence.substring(0, length-1); return isPalindrome(shorter); } else { String shorter = sentence.substring(1); return isPalindrome(shorter); } } } 

被称为:

 System.out.println(r.isPalindrome("Madam, I'm Adam")); 

如果回文将打印为true,否则将打印为false。

如果字符串的长度为0或1(不再需要检查的字符串),则返回true,作为基本情况。 此基本情况将在此之前通过函数调用引用。 然后通过在每次递归调用函数时切掉第一个和最后一个字母来比较以查看第一个和最后一个字母是否相等。

这是没有创建许多字符串的回文检查的代码

 public static boolean isPalindrome(String str){ return isPalindrome(str,0,str.length()-1); } public static boolean isPalindrome(String str, int start, int end){ if(start >= end) return true; else return (str.charAt(start) == str.charAt(end)) && isPalindrome(str, start+1, end-1); } 

公共类PlaindromeNumbers {

 int func1(int n) { if(n==1) return 1; return n*func1(n-1); } static boolean check=false; int func(int no) { String a=""+no; String reverse = new StringBuffer(a).reverse().toString(); if(a.equals(reverse)) { if(!a.contains("0")) { System.out.println("hey"); check=true; return Integer.parseInt(a); } } // else // { func(no++); if(check==true) { return 0; } return 0; } public static void main(String[] args) { // TODO code application logic here Scanner in=new Scanner(System.in); System.out.println("Enter testcase"); int testcase=in.nextInt(); while(testcase>0) { int a=in.nextInt(); PlaindromeNumbers obj=new PlaindromeNumbers(); System.out.println(obj.func(a)); testcase--; } } 

}

 /** * Function to check a String is palindrome or not * @param s input String * @return true if Palindrome */ public boolean checkPalindrome(String s) { if (s.length() == 1 || s.isEmpty()) return true; boolean palindrome = checkPalindrome(s.substring(1, s.length() - 1)); return palindrome && s.charAt(0) == s.charAt(s.length() - 1); } 

简单解决方案 2场景 – (奇数或偶数长度字符串)

基本条件和Algo递归(ch,i,j)

  1. 我== j //甚至是len

  2. if i

  3. else return ch [i] == ch [j] //旧长度的额外基本条件

 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)); } } 

为了实现这一点,您不仅需要了解递归的工作原理,还需要了解String方法。 这是我用来实现它的示例代码: –

 class PalindromeRecursive { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter a string"); String input=sc.next(); System.out.println("is "+ input + "a palindrome : " + isPalindrome(input)); } public static boolean isPalindrome(String s) { int low=0; int high=s.length()-1; while(low