c# - 不使用辅助函数的回文递归?

标签 c# .net recursion

我写了一个递归来检查一个字符串是否是回文:

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/

相关文章:

c# - BeautifulSoup 和 ASP.NET/C#

c# - 比较两个数据行

c# - Entity Framework 更新问题

.net - 并行时 WCF 服务变慢

caching - 如何使用 Y-combinator 为这个函数获取缓存

c - 在递归函数中修改二维数组,C

python - 递归地将项目添加到列表中

c# - 如果 IP 地址或主机名是本地主机,如何检查 Powershell?没有域 DNS

.net - 结构到字节数组以通过套接字发送

c# - Azure Web 应用程序上的 Office 组件安装