创建回文的递归方法

发布于 2024-10-06 03:14:49 字数 748 浏览 6 评论 0 原文

我正在尝试在 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;
  }
 }
}

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

二智少女猫性小仙女 2024-10-13 03:14:50

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

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);
}
我三岁 2024-10-13 03:14:50
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;
} 
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;
} 
再可℃爱ぅ一点好了 2024-10-13 03:14:50

试试这个:

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

    }

}

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

    }

}
表情可笑 2024-10-13 03:14:50
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...");
}
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...");
}
吻风 2024-10-13 03:14:50
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 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");
     }
}
深白境迁sunset 2024-10-13 03:14:50

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

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() 方法。

Here is a recursive method that will ignore specified characters:

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

Use it like this:

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

It does not make sense to include case insensitivity in the recursive method since it only needs to be done once, unless you are not allowed to use the .toLowerCase() method.

淡淡離愁欲言轉身 2024-10-13 03:14:50

没有比这更小的代码了:

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

LOL B-]

there's no code smaller than this:

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

if you want to check something:

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

LOL B-]

孤蝉 2024-10-13 03:14: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;
    }

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

我喜欢@JigarJoshi 的答案,但他的方法的唯一问题是,对于包含大写字母的单词,它会给你错误的结果。

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.

甜味拾荒者 2024-10-13 03:14:50

回文示例:

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,作为基本情况。在此之前的函数调用将引用此基本情况。然后通过每次递归调用函数时截掉第一个和最后一个字母来比较第一个和最后一个字母是否相等。

Palindrome example:

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

Called by:

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

Will print true if palindrome, will print false if not.

If the length of the string is 0 or 1(no more string to check), return true, as the base case. This base case will be referred to by function call right before this. 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.

彡翼 2024-10-13 03:14:50

这是在不创建许多字符串的情况下进行回文检查的代码

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

Here is the code for palindrome check without creating many strings

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);
}
乖乖 2024-10-13 03:14:50

公共类 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--;
   }
}

}

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

}

树深时见影 2024-10-13 03:14:50
/**
     * 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);

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

    }
我家小可爱 2024-10-13 03:14:50

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

基本条件&算法递归(ch, i, j)

  1. i==j //偶数len

  2. if i<; j 递归调用 (ch, i +1,j-1)

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

公共类HelloWorld {


 静态布尔 ispalindrome(char ch[], int i, int j) {
  if (i == j) 返回 true;

  如果(i


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

 }
}
栀子花开つ 2024-10-13 03:14:50

为了实现这一点,您不仅需要知道递归的工作原理,还需要了解 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<high)
    {
      if(s.charAt(low)!=s.charAt(high))
      return false;
      isPalindrome(s.substring(low++,high--));
    }

    return true;
  }
}

for you to achieve that, you not only need to know how recursion works but you also need to understand the String method.
here is a sample code that I used to achieve it: -

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<high)
    {
      if(s.charAt(low)!=s.charAt(high))
      return false;
      isPalindrome(s.substring(low++,high--));
    }

    return true;
  }
}
扮仙女 2024-10-13 03:14:49

我在这里为您粘贴代码:

但是,我强烈建议您了解它是如何工作的,

从您的问题来看,您完全无法阅读。

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

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

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");
    }
}
北凤男飞 2024-10-13 03:14:49

嗯:

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

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

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.

生来就爱笑 2024-10-13 03:14:49
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;
 }

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

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.

前事休说 2024-10-13 03:14:49

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

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

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);
}
淡淡的优雅 2024-10-13 03:14:49

这是我的做法:

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

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"));
    }
}
柠檬心 2024-10-13 03:14:49
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");
    }
}
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");
    }
}
单挑你×的.吻 2024-10-13 03:14:49

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

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

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));
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文