我在阅读平衡括号挑战错了吗?

时间:2017-01-26 07:45:22

标签: c# .net algorithm data-structures

我正在做平衡括号问题(https://www.hackerrank.com/challenges/balanced-brackets)而我无法弄清楚我出错的地方。

e.g。

3
{[()]}
{[(])}
{{[[(())]]}}

- >

YES
NO
YES

我认为这个字符串包含平衡括号是一个直截了当的事实,当且仅当每一对s[i],s[n-i-1]确实s[i]是一个右向括号并且s[n-i-1]是相应的左向括号。

因此我的解决方案

static readonly Dictionary<char,char> brackets = new Dictionary<char,char>() 
{
    { '{', '}' },
    { '[', ']' },
    { '(', ')' }
};

static bool IsBalanced(string str)
{
    for(int i = 0, j = str.Length - 1; i < j; ++i, --j)
        if(!brackets.ContainsKey(str[i]) || brackets[str[i]] != str[j])
            return false;
    return true;
}

由于某种原因失败了。

3 个答案:

答案 0 :(得分:6)

典型的实现基于 stack

  • 将任何打开 [{(括号推送到堆栈
  • 关于关闭 ]})括号,尝试弹出顶部项目并检查它是否与当前结束括号相对应:{{ 1}}到(等。如果堆栈为空,则返回)没有对应
  • 最后,在处理完最后一个字符后,堆栈应该为空

实现:

false

答案 1 :(得分:0)

为什么你的代码得到了错误的答案?

您在案例str = "()()"上收到的答案错误。

问题的解决方案

你可以解决使用递归问题 让isBalanced(l, r)是字符串str[l] + str[l+1] + ... + str[r-1]是否平衡,你可以像这个代码(c ++)那样做并计算isBalanced(0, str.Length)

bool isBalanced(int l, int r) {
    if(l == r) return true;
    int depth = 0, prevptr = l;
    for(int i = l; i < r; i++) {
        if(str[i] == '(' || str[i] == '{' || str[i] == '[') depth++;
        else depth--;
        if(i != r - 1 && depth == 0) {
            if(!isBalanced(prevptr, i + 1)) return false;
            prevptr = i + 1;
        }
    }
    if(depth != 0) return false;
    if(prevptr != l) {
        if(!isBalanced(prevptr, r)) return false;
        return true;
    }
    bool ok = false;
    if(str[l] == '(' && str[r - 1] == ')') ok = true;
    if(str[l] == '{' && str[r - 1] == '}') ok = true;
    if(str[l] == '[' && str[r - 1] == ']') ok = true;
    if(!ok || !isBalanced(l + 1, r - 1)) return false;
    return true;
}

我知道你是C#编码器,但很多C#编码器都可以读C ++代码,所以我用C ++实现(因为我是C ++编码器)

答案 2 :(得分:0)

我已经通过使用堆栈解决了JavaScript中的问题

class Stack extends Array {
    constructor(...ele) {
        super(...ele)
    }
    pop()
    {
        if(this.length === 0) throw new Error("nothing to pop");
        super.pop()
     }
    peek() {
        if(this.length === 0) throw new Error("stack is empty");
        return this[this.length - 1];
    }
    size() {
        return this.length;
    }
}

const string1 = '{[]}'
function check(string) {
    const stack = new Stack();
    const arr = string.split('');
    for(let i=0; i<arr.length; i++) {
        const currentItem = arr[i];
        if(currentItem === '{' || currentItem === '[' || currentItem === '(') {
            stack.push(currentItem);
        }
        else {  // ],},)
            if(stack.size() === 0) {
                return false;
            }
            const lastItem = stack.peek();
            stack.pop();
            if(lastItem === '{' && currentItem === '}')
            {
                //ok
            }
            else if(lastItem === '[' && currentItem === ']'){
                //ok
            }
            else if(lastItem === '(' && currentItem === ')') {
                //ok
            }
            else {
                return false;
            }
        }
    }
    if (stack.size() !== 0) {
        return false;
    }
    return true;
}

console.log(check(string1))