简体   繁体   English

为什么我的字符数组的就地递归代码不适用于所有测试用例? 我的代码有什么问题

[英]why my code of inplace recursion of character array is not working for all the test cases? is there any problem with my code

class Solution { 
    static int k=0; 
    static int l=0; 

    public void reverseString(char[] s) { 
        if(k==s.length||s==null){ 
            return; 
        }

        char c = s[k++]; 
        reverseString(s); 
        s[l++]=c; 
    } 
}

why my code of inplace recursion of character array is not working for all the test cases? 为什么我的字符数组的就地递归代码不适用于所有测试用例? is there any problem with my code 我的代码有什么问题

Instead of using a class that has to be instantiated to reverse the array, I would suggest the following: 我建议不要使用必须实例化的类来反转数组,而是使用以下内容:

class Solution {

   public static void reverseString(char[] str) {
      reverseStringImpl(str, 0);
   }

   private static void reverseStringImpl(char[] s, int k) {
      // details here
   }
}

I omitted the details (but the array and starting location are sufficient to accomplish this). 我省略了细节(但数组和起始位置足以完成此任务)。 This is still recursive but it hides the implementation and does not require any instance variables to maintain state . 这仍然是递归的,但它隐藏了实现,并且不需要任何instance variables来维护state Nor does it require the user to pass the initial starting location of 0 to the method. 它也不要求用户将0的初始起始位置传递给方法。

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

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