2010/2/12 newbiecoder <[email protected]>:
> I am having trouble mastering the concept of recursion...does anyone
> here have any advice / excellent articles to share???
>
>
> I don't understand how to create a recursion for this palindrome
> method given this format
> Palindrome(string str, int start, int end)
>
> Not sure if the code below is the proper way. It does not work if
> 'end' is an odd number....
>
>
> public static bool Palindrome(string str, int start, int end)
>        {
>            bool result = false;
>
>            if (start == end)
>
>
>                { return true; }
>
>
>            else if (str[start] == str[end])
>
>            { result = Palindrome(str, start + 1, end - 1); }
>
>
>
>            else
>                result = false;
>
>
>            return result;
>
>
>        }
>


Hi,

You just need to verify if end is lower than start.

It should be:

public static bool Palindrome(string str, int start, int end)
        {
            bool result = false;

            if (start == end || end < start)
            {
                return true;
            }
            else if (str[start] == str[end])
            {
                result = Palindrome(str, start + 1, end - 1);
            }
            else
            {
                result = false;
            }

            return result;
        }

Take in count that if "str.Length" is even, you will never have "start
== end". On next recursive call, end will be lower than start, and it
means it checked all chars until that point and were equals, so it's a
palindrome string (start and end intersected).

Sorry about my english. ;(


-- 
Oscar Mederos

Reply via email to