一些更高级的递归

时间:2012-11-29 07:30:13

标签: java

我一直在寻找一段时间,而且我找不到任何帮助我的东西。我必须编写一个程序,它使用一个方法(主方法)来读取数组的大小和/和元素。然后我必须写一个标题为“forwardsEqualBackwards”的递归方法,如果无论数组是向前还是向后读取,都可以以相同的方式读取数组的元素,返回 true (这是一个测试,看看是否或者不是它的回文),否则就是假的。

2 个答案:

答案 0 :(得分:2)

伪代码:

bool forwardsEqualBackwards(array a, int length, int indexToLookAt=0)
{
  if (indexToLookAt >= length-indexToLookAt-1)
    return true; //reached end of recursion
  if (a[indexToLookAt] == a[length-indexToLookAt-1])
    return forwardsEqualBackwards(a,length, indexToLookAt+1); //normal recursion here
  else 
    return false;
}

forwardsEqualBackwards("",0);  //returns true
forwardsEqualBackwards("a",1);  //returns true
forwardsEqualBackwards("otto",4);  //returns true
forwardsEqualBackwards("otsto",5);  //returns true
forwardsEqualBackwards("otstou",5);  //returns false

答案 1 :(得分:1)

bool method(int start, int end)
{
     if(start<=end)
     {
           if(Array[start]!=array[end])
                 return false;
           return method(start+1, end-1)
     }
     return true;

}
相关问题