用递归进行回文检查 [英] Palindrome check with recursion

查看:51
本文介绍了用递归进行回文检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习递归并尝试进行回文检查.它不工作.谁能帮我找出原因.

I was learning about recursion and was attempting a palindrome check. It is not working. Can someone help me figure out the reason.

private static bool CheckPalin(string p)
{
    if(p.Length == 1 || p.Length == 0)  //added check for even cases
        return true;
    if(p[0] != p[p.Length -1])
        return false;

    CheckPalin(p.SubsString(1, p.Length -2));
    return true;
}

推荐答案

丹击中了一个失败 方块在头上(正如我关于 aa 的问题所暗示的那样——长度 0 字符串会给你带来麻烦).

Dan hit one failure square on the head (as implied by my question about aa -- length 0 strings will give you trouble).

另一种失败情况,如误报所示,一旦您快速退后一步寻找它,实际上非常明显:

The other failure case, as indicated by false positives is actually pretty obvious once you take a quick step back and look for it:

CheckPalin(p.SubsString(1, p.Length -2));
return true;

试试:

return CheckPalin(p.SubsString(1, p.Length -2));

太棒了,我在没有注意到的情况下浏览了两次 - 直到您指出误报.:)

It's amazing, I skimmed it twice without noticing it -- until you pointed out the false positives. :)

这篇关于用递归进行回文检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆