相关疑难解决方法(0)

检查字符串具有平衡括号

我正在阅读算法设计手册第二版,这是一个练习题.引用问题

编译器和文本编辑器的一个常见问题是确定字符串中的括号是否是平衡的并且是否正确嵌套.例如,字符串((())())()包含正确嵌套的括号对,字符串)()(和())不包含.如果字符串包含正确嵌套和平衡的括号,则给出一个返回true的算法,否则返回false.对于完全信用,如果字符串未正确嵌套和平衡,则标识第一个违规括号的位置.

问题在堆栈,队列和列表类别下.这是我在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() + …
Run Code Online (Sandbox Code Playgroud)

c# algorithm

14
推荐指数
3
解决办法
3万
查看次数

标签 统计

algorithm ×1

c# ×1