【问题标题】:Recursively reverse an array of strings递归反转字符串数组
【发布时间】:2013-04-25 23:31:56
【问题描述】:

创建并返回一个新数组,该数组是作为参数传递的数组的反向副本。

我的代码如下。我被算法困住了?这是一道考试题,但现在考试已经结束了。

import java.util.*;

public class Q4_ArrayReverse
{
   public static String[] reverse( String[] in )
   {
      String[] out = new String[ in.length ];
      reverse( in, out, 0 );
      return out;
   }
   ///////////////////////////////////////////////////////////
   //
   // Given an input array, an output array and an index,
   //    copy the element at the index offset of the input array
   //    to the appropriate reversed position in the output array.
   //    i.e. in[ 0 ] -> out[ n - 1 ]
   //         in[ 1 ] => out[ n - 2 ]
   //            etc.
   //    After doing the copy for index, recurse for index + 1
   //    Be sure to quit when you get to the end of the array.
   //
   //////////////////////////////////////////////////////////
   static void reverse( String[] in, String[] out, int index )
   {







   }

【问题讨论】:

  • 好吧,把它分解成它的组件。在递归中,总是需要有一个终止条件。
  • Q4_ArrayReverse 是一个讨厌的类名,不符合 Java 命名约定。

标签: java arrays recursion


【解决方案1】:

在您的第二种(当前为空白)方法中,您需要在将索引indexin.length - index - 1 放入新的out 数组时交换它们。然后当然你想对index + 1 做同样的事情,除非你在数组的中间,在这种情况下你已经完成并且可以返回。

if (index == array.length / 2)  // i.e. 1 position past the middle
    return

out[index] = in[in.length - index - 1];
out[in.length - index - 1] = in[index];

reverse(in, out, index+1);

【讨论】:

  • if (index == in.length) // 即超过中间返回 1 个位置; out[out.length - (index + 1)] = in[index];反向(输入,输出,索引+1);事实证明这已经足够了,不知道为什么不需要 array.length/2。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-26
  • 1970-01-01
  • 2013-02-25
  • 2015-08-15
  • 2017-07-20
相关资源
最近更新 更多