gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:21:12 25 4
gpt4 key购买 nike

程序需要使用递归检查数组是否为回文,但我在非托管中得到堆栈溢出异常。卡了一天多了,求助

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++);
}

最佳答案

你在增量中有错误;它应该是 ++index 而不是 index++:

return Rowpalindrome(arr, ++index);

您应该递增并传递 index (++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);

关于c# - 为什么在非托管错误中出现堆栈溢出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53059687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com