我正在尝试使用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;
}
}
}
任何人都可以为我的问题提供解决方案吗?
答案 0 :(得分:35)
我在这里为您粘贴代码:
但是,我强烈建议你知道它是如何运作的,
从你的问题来看,你完全不可读。尝试理解此代码。 阅读代码中的评论
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");
}
}
答案 1 :(得分:5)
好:
我现在不会比现在更清楚地说出来,因为我怀疑这是作业 - 事实上有些人可能认为上面的帮助太多了(我当然有点犹豫不决)。如果您对上述提示有任何问题,请更新您的问题以显示您已经有多远。
答案 2 :(得分:4)
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;
}
也许你需要这样的东西。没有测试,我不确定字符串索引,但它是一个起点。
答案 3 :(得分:3)
我认为,递归并不是解决这个问题的最佳方法,但我在这里看到的一种递归方式如下所示:
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);
}
答案 4 :(得分:1)
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");
}
}
答案 5 :(得分:1)
有些代码很重。我们可以在递归调用中传递索引,而不是创建创建新对象的子字符串:
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));
}
答案 6 :(得分: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"));
}
}
答案 7 :(得分:0)
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;
}
答案 8 :(得分:0)
试试这个:
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");
}
}
答案 9 :(得分:0)
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...");
}
答案 10 :(得分:0)
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");
}
}
答案 11 :(得分:0)
以下是三个简单的实现,首先是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);
}
答案 12 :(得分:0)
这是一个忽略指定字符的递归方法:
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()
方法。
答案 13 :(得分:0)
没有比这更小的代码:
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 - ]
答案 14 :(得分:0)
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;
}
此解决方案不区分大小写。因此,例如,如果您有以下单词:&#34; adinida&#34;,那么如果您这样做,那么您将会成为&#34; Adninida&#34;或&#34; adninida&#34;或者&#34; adinidA&#34;,这就是我们想要的。
我喜欢@JigarJoshi的答案,但他的方法唯一的问题是,它会给你包含上限的单词的假。
答案 15 :(得分:0)
Palindrome示例:
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,作为基本情况。此基本情况将在此之前通过函数调用引用。然后比较以查看第一个和最后一个字母是否相等,每次递归调用该函数时都会切掉第一个和最后一个字母。
答案 16 :(得分:0)
以下是没有创建许多字符串的回文检查代码
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);
}
答案 17 :(得分:0)
公共类PlaindromeNumbers {
<div contenteditable="true" id="likeInput" disabled="disabled"><?php include 'outsidefile.php'; ?></div>
}
答案 18 :(得分:0)
/**
* 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);
}
答案 19 :(得分:0)
简单解决方案 2场景 - (奇数或偶数长度字符串)
基本条件&amp; Algo递归(ch,i,j)
i == j // even len
如果我&lt; j recurve call(ch,i + 1,j-1)
否则返回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)); } }
答案 20 :(得分:0)
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;
}
}