簡體   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