在C#中编写递归函数

时间:2013-11-22 05:20:16

标签: c# recursion

我需要编写一个函数来验证括号是否在字符串中平衡。每个开括号应该有一个相应的近括号,它们应该正确对应。

例如,对于以下字符串,函数应返回true:

  

(if(any?x)sum(/ 1 x))

     

我说(它还没有完成)。 (她不听)

     

对于以下字符串,该函数应返回false:

     

: - )

     

())(

可选奖金

将解决方案实现为递归函数,没有突变/副作用。

请你用C#帮我写信,因为我是.NET技术的新手。

感谢。

这是我到目前为止所尝试的内容。它适用于将参数作为开括号和近括号发送,但我只是传递一个字符串...而且我也不应该使用堆栈。

private static bool Balanced(string input, string openParenthesis, string closedParenthesis)
    {

        try
        {
            if (input.Length > 0)
            {
                //Obtain first character
                string firstString = input.Substring(0, 1);

                //Check if it is open parenthesis
                //If it is open parenthesis push it to stack
                //If it is closed parenthesis pop it
                if (firstString == openParenthesis)
                    stack.Push(firstString);
                else if (firstString == closedParenthesis)
                    stack.Pop();

                //In next iteration, chop off first string so that it can iterate recursively through rest of the string
                input = input.Substring(1, input.Length - 1);
               Balanced(input, openParenthesis, closedParenthesis);   //this call makes the function recursive
            }

            if (stack.Count == 0 && !exception)
                isBalanced = true;
        }
        catch (Exception ex)
        {
            exception = true;
        }

        return isBalanced;
    }

3 个答案:

答案 0 :(得分:4)

对于这样一个简单的要求,你不需要使用任何递归方法,只需尝试这个简单的方法,它就像一个魅力:

public bool AreParenthesesBalanced(string input) {
  int k = 0;
  for (int i = 0; i < input.Length; i++) {
      if (input[i] == '(') k++;
      else if (input[i] == ')'){
        if(k > 0)  k--;
        else return false;
      }
  }
  return k == 0;
}

答案 1 :(得分:2)

我使用了startIndex并在每次递归调用时递增

  List<string> likeStack = new List<string>();
  private static bool Balanced(string input, string openParenthesis, string closedParenthesis , int startIndex)
{

    try
    {
        if (startIndex < input.Length)
        {
            //Obtain first character
            string firstString = input.Substring(startIndex, 1);

            //Check if it is open parenthesis
            //If it is open parenthesis push it to stack
            //If it is closed parenthesis pop it
            if (firstString == openParenthesis)
                likeStack.Add(firstString);
            else if (firstString == closedParenthesis)
                likeStack.RemoveAt(likeStack.Count -1);

            //In next iteration, chop off first string so that it can iterate recursively through rest of the string
           Balanced(input, openParenthesis, closedParenthesis , startIndex + 1);   //this call makes the function recursive
        }

        if (likeStack.Count == 0 && !exception)
            isBalanced = true;
    }
    catch (Exception ex)
    {
        exception = true;
    }

    return isBalanced;
}

答案 2 :(得分:2)

这个递归版本怎么样?

    public static bool Balanced(string s)
    {
        var ix = -1;
        return Balanced(s, false, ref ix);
    }

    private static bool Balanced(string s, bool inParens, ref int ix)
    {
        ix++;
        while (ix < s.Length)
        {
            switch (s[ix++])
            {
                case '(':
                    if (!Balanced(s, true, ref ix))
                        return false;
                    break;
                case ')':
                    return inParens;
            }
        }

        return !inParens;
    }