java - 为回文创建递归方法

标签 java recursion palindrome

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

谁能解决我的问题?

最佳答案

我在这里为您粘贴代码:

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

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

尝试理解这段代码。 从代码中读取注释

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

关于java - 为回文创建递归方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4367260/

相关文章:

C 函数,它接收一个结构,并导致它在函数外部发生变化,即使该结构没有作为指针发送

c++ - 由两个 3 位数的乘积组成的所有回文数

java - 在java中将ppt文件转换为PDF时出错

java - 使用 SSL 访问 Web 服务时出错

ruby - 如何从 Ruby 中的阶乘方法中排除 float ?

python - 点积的递归应用

java - 回文单词未正确显示

java - 使用 Sitebricks 发送一致的 JSON 响应来报告异常

java - Spring 时区问题中的 DateTimeFormat 注释

javascript - 是什么导致我的 jQuery 调用出现这种递归?