繁体   English   中英

递归地反转字符串数组

[英]Recursively reverse an array of strings

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

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

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 )
   {







   }

在第二种方法(当前为空白)中,将元素放入新的out数组中时,需要在索引indexin.length - index - 1处交换它们。 然后当然要对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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM