【发布时间】: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 ...