Java 为回文创建递归方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4367260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 16:36:13  来源:igfitidea点击:

Creating a recursive method for Palindrome

javarecursionpalindrome

提问by Nightshifterx

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

我正在尝试使用 Java 中的递归创建一个回文程序,但我被卡住了,这是我到目前为止所拥有的:

 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?

任何人都可以为我的问题提供解决方案吗?

采纳答案by Jigar Joshi

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

回答by Jon Skeet

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 orany 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 oneway of doing it, but it's far from the only way.
  • 不清楚为什么你有两个具有相同签名的方法。他们要完成什么?
  • 在第一种方法中,为什么要测试单个空格任何单个字符?
  • 您可能需要考虑将终止条件概括为“如果长度小于 2”
  • 考虑你想如何递归。一种选择:
    • 检查第一个字母是否等于最后一个字母。如果不是,返回false
    • 现在取一个子串来有效地去除第一个和最后一个字母,然后递归
  • 这是否意味着递归练习?这当然是一种方法,但它远不是唯一的方法。

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.

我暂时不会比这更清楚地说明它,因为我怀疑这是家庭作业 - 事实上有些人可能认为上面的帮助太多(我自己当然有点犹豫)。如果您对上述提示有任何问题,请更新您的问题以显示您已经走了多远。

回答by mauretto

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.

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

回答by Roman

I think, recursion isn't the best way to solve this problem, but one recursive way I see here is shown below:

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

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

回答by aioobe

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

回答by HaskellElephant

Here are three simple implementations, first the oneliner:

这是三个简单的实现,首先是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);
}

回答by brian maphosa

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

回答by Naresh

Try this:

尝试这个:

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

    }

}

回答by Naresh

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

回答by Karthik N S

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