【问题标题】:Writing a recursive function in C#用 C# 编写递归函数
【发布时间】:2013-12-06 21:38:58
【问题描述】:

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

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

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

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

该函数应为以下字符串返回 false:

:-)

())(

可选奖金

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

由于我是 .NET 技术的新手,请您帮助我使用 C# 编写代码。

谢谢。

这是我迄今为止尝试过的。它适用于将参数作为左括号和右括号发送,但我对仅传递字符串感到困惑......而且我也不应该使用堆栈。

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;
    }

【问题讨论】:

  • 你能告诉我们你做了什么吗?我们可以帮助你,但我们不会为你做作业:D
  • 请在此处找到我的代码,该代码可用于将参数作为左括号和右括号发送。但我对只传递一个字符串感到困惑......而且我也不应该使用堆栈
  • 只是一个建议,你可以使用str[0]代替string.substring(0,1),并用'{'而不是“{”来检查。
  • 提示:使用Stack。它会让你的生活变得轻松。 en.wikipedia.org/wiki/Stack_%28abstract_data_type%29
  • 我会改变:Can you please help me out in writing using C# because I'm new to .NET technologies.can you please do this for me because I want the extra credit ...

标签: c# recursion


【解决方案1】:

这个递归版本怎么样?

    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;
    }

【讨论】:

    【解决方案2】:

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

    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;
    }
    

    【讨论】:

    • 可能是 "foreach(Char letter in input)" 会比 "for(int i = 0;..." 循环格式略好阅读
    • @DmitryBychenko 同意!
    【解决方案3】:

    我在每次递归调用中都使用了 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;
    }
    

    【讨论】:

    • @rajeshAlbert 可以使用 List 吗,因为堆栈使用的是 LIFO,我们也可以使用 list 来实现。我使用 List 而不是堆栈更新了我的代码。看看吧
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    • 2015-05-12
    • 1970-01-01
    相关资源
    最近更新 更多