回文递归计划 [英] Palindrome Recursion Program

查看:92
本文介绍了回文递归计划的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static boolean palindrome(String input, int i, int j)
 {
  if (i >= j)
   return true;
  if (input.charAt(i) == input.charAt(j))
  {
   i++;
   j--;
   palindrome(input, i, j);
  }
  else if (input.charAt(i) != input.charAt(j))
   return false;
 }

由于缺少返回类型",我的Java平台(eclipse)无法接受此代码.现在,我知道在适当的编码前提下,最好只使用一个返回值,但是对于递归而言,这对我来说有点新.我该怎么做呢?如果我在此方法的顶部实例化一个布尔类型,则每次该方法运行时都会创建该变量的新实例(并将其实例化为null或将其设置为它的任何值),但是如果我将其放置在构造函数上方,方法不会为其分配值/无法返回它.

My Java platform (eclipse) won't accept this code as working, due to a "lack of return type." Now I know in proper coding ediquite, it's better to use only one return value, but when it comes to recursion, this is somewhat new to me. How can I go about doing this? If I instantiate a Boolean type at the top of this method, it's creating a new instance of that variable (and instantiating it as null or whatever I set it to) each time the method runs, but if I place it above my constructor, my method won't assign a value to it/can't return it.

基本上,我该如何修改我的代码以使其具有Eclipse将始终执行的单个返回值?我可以使用循环很容易地做到这一点,但是我不确定如何使用递归来解决这个问题.

Basically, how do I go about modifying my code to have a single return value that Eclipse will accept as always executing? I can do this easily enough with loops, but I'm not sure how to approach the topic with Recursion.

推荐答案

您当然可以这样做:

return palindrome(input, i, j);

但是,优良作法是单独返回以提高可读性.试试看它的大小:

However it is good practice to have a single return to improve readability. Try this on for size:

   boolean isPalindrome = false; 
   if (i >= j)
   isPalindrome = true;
   else if (input.charAt(i) == input.charAt(j))
  {
   i++;
   j--;
   isPalindrome = palindrome(input, i, j);
  }
  else if (input.charAt(i) != input.charAt(j))
   isPalindrome = false;
  return isPalindrome;
 }

始终实例化该布尔值.这里的关键是使回文集的返回值存储在该布尔值中.

Have that boolean always instantiated. The key here is to make palindrome's return be stored in that boolean.

递归部分出现在回文调用中.它只会在所有递归调用之后最终返回最终值,因为它只有在到达递归循环结束时才确定其回文.

The recursive portion comes in at the call to palindrome. It will only finally return the final value after all of the recursive calls, because it only ever determines if its a palindrome when it reaches the end of the recursive cycle.

这篇关于回文递归计划的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆