为什么在非托管错误中出现堆栈溢出异常

时间:2018-10-30 07:55:49

标签: c# recursion

程序需要使用递归检查数组是否是回文,但是在不受管的情况下,我会得到堆栈溢出异常。坚持了一天以上,请帮忙

public static void Main(string[] args)
{
    char[] arr = { 'd', 'a', 'd' };
    int ind = 0;

    Rowpalindrome(arr, ind);
}

static bool Rowpalindrome(char[] arr, int index)
{
    if (index == arr.Length % 2)
        return true;

    int i = index;

    if (arr[i] != arr[(arr.Length - index - 1)])
        return false;
    else
        return Rowpalindrome(arr, index++);
}

1 个答案:

答案 0 :(得分:7)

您在增量中有错误;应该是++index而不是index++

return Rowpalindrome(arr, ++index);

您应该增加并传递index++index修改值,而不是增加并传递 initial 值(index++ )。更好的实现是将其设置为简单

return Rowpalindrome(arr, index + 1);

编辑:您也有一些逻辑错误(感谢Fildor指出了该错误):条件应该是

if (arr.Length <= 1 || index > arr.Length % 2 + 1)
    return true;

最终的话语代码可以是

static bool Rowpalindrome(char[] arr, int index) {
  if (arr.Length <= 1 || index > arr.Length % 2 + 1)
    return true;

  // Let's get rid of "i" (which is index) and exploit short circuit of &&:
  // .Net tests arr[index] != arr[(arr.Length - index - 1)]
  // and only if it's true call for Rowpalindrome(arr, index + 1)
  return arr[index] != arr[(arr.Length - index - 1)] && Rowpalindrome(arr, index + 1);
}

测试用例:(让我们使用 Linq 查询每个测试)

using System.Linq;

...

var tests = new char[][] {
  new char[] { },
  new char[] { 'a' },
  new char[] { 'a', 'a' },
  new char[] { 'a', 'b' },
  new char[] { 'a', 'b', 'a' },
  new char[] { 'a', 'b', 'c' },
  new char[] { 'a', 'b', 'b', 'a' },
  new char[] { 'a', 'b', 'c', 'a' },
  new char[] { 'a', 'b', 'b', 'c' },
};

var result = tests
  .Select(test => $"{"[" +string.Join(", ", test) + "]", -15} : {(Rowpalindrome(test, 0) ? "Palindrome" : "Not")}");

Console.Write(string.Join(Environment.NewLine, result));

结果:

[]              : Palindrome
[a]             : Palindrome
[a, a]          : Palindrome
[a, b]          : Not
[a, b, a]       : Palindrome
[a, b, c]       : Not
[a, b, b, a]    : Palindrome
[a, b, c, a]    : Not
[a, b, b, c]    : Not

编辑2:如果是多维数组(请参见下面的注释),则可以将感兴趣的列提取到数组中并运行例程,例如用于2D数组:

char[,] c = new char[,] {
  { 'a', 'b', 'c'},
  { 'x', 'y', 'z'},
  { 'x', 'p', 'q'},
  { 'a', 'm', 'n'},
};

int colIndex = 0; // should be {'a', 'x', 'x', 'a'} column

// c.GetLength(0) - number of lines (length of the 1st dimension) - 4
char[] a = new char[c.GetLength(0)];

for (int i = 0; i < a.Length; ++i)
  a[i] = c[i, colIndex];

bool result = Rowpalindrome(a, 0);
相关问题