【发布时间】:2009-09-04 17:38:55
【问题描述】:
我正在阅读算法设计手册第二版,这是一个练习题。引用问题
编译器的常见问题和 文本编辑器正在确定是否 字符串中的括号是 平衡和正确嵌套。为了 例如,字符串 ((())())() 包含正确嵌套的对 括号,其中字符串 )()( 也不要。给出一个算法 如果字符串包含,则返回 true 正确嵌套和平衡 括号,否则为假。 要获得完整的信用,请确定职位 第一个有问题的括号如果 字符串没有正确嵌套并且 平衡。
问题属于堆栈、队列和列表类别。这是我用 C# 写的。
const char LeftParenthesis = '(';
const char RightParenthesis = ')';
bool AreParenthesesBalanced(string str, out int errorAt)
{
var items = new Stack<int>(str.Length);
errorAt = -1;
for (int i = 0; i < str.Length; i++)
{
char c = str[i];
if (c == LeftParenthesis)
items.Push(i);
else if (c == RightParenthesis)
{
if (items.Count == 0)
{
errorAt = i + 1;
return false;
}
items.Pop();
}
}
if (items.Count > 0)
{
errorAt = items.Peek() + 1;
return false;
}
return true;
}
这很好用。但我不确定这是解决这个问题的正确方法。欢迎任何更好的想法。
【问题讨论】:
-
可以查看refactormycode.com,它更适合这类事情。
-
是的,这是非常正确的方法,也用于解析数学表达式。