我写了一个递归来检查一个字符串是否是回文:
public static bool IsPalindrome(string value)
{
if ( value == null )
return false;
if ( value.Length == 0 )
return true;
return isPalindrome(value, 0, value.Length - 1);
}
private static bool isPalindrome(string value, int startChar, int endChar)
{
if ( value[startChar] != value[endChar] )
return false;
if ( startChar >= endChar )
return true;
return isPalindrome(value, startChar + 1, endChar - 1);
}
但是我试图找到一种方法来执行相同的算法而不使用执行递归的辅助方法 (isPalindrome(.. , .. , ..)
) 但是我仍然需要调用isPalindrome(...)
的。
如何将这两个函数合并为一个,递归算法不会调用任何其他函数?
最佳答案
用匿名方法替换单独的方法是否可以接受:
public static bool IsPalindrome(string value)
{
if (value == null)
return false;
if (value.Length == 0)
return true;
Func<string, int, int, bool> ip = null;
ip = (v, sc, ec) =>
{
if (v[sc] != v[ec])
return false;
if (sc >= ec)
return true;
return ip(v, sc + 1, ec - 1);
};
return ip(value, 0, value.Length - 1);
}
关于c# - 不使用辅助函数的回文递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33970276/