【问题标题】:Write a method that takes a string of curly brackets and returns true if the brackets match up and false if they don’t编写一个方法,接收一串花括号,如果括号匹配则返回 true,否则返回 false
【发布时间】:2017-11-09 09:15:36
【问题描述】:

我在 CodeHS 中解决了这个问题,我必须编写一个方法,该方法接受一串花括号,如果括号匹配则返回 true,否则返回 false。

到目前为止,这是我的编码,当左大括号和右大括号的数量相同时,我不知道该怎么办,但这些只是不匹配,例如(}}{{)。

public boolean bracketsMatch(String brackets)
{
    boolean result = true;
    int leftCtr = 0 ;  //"{";
    int rightCtr =0 ; // "}";
    int count = 0;

    for (int i=0; i<brackets.length(); i++)
    {
        char c = brackets.charAt(i);
        if ( c == '{')
        {
           leftCtr++;
        }
        if (c =='}')
        {
            rightCtr++;
        }
    }

    if (rightCtr==leftCtr)
    {
        result= true;
    }
    else 
    {
        return false;
    }

    return result;
}

谢谢

【问题讨论】:

  • 平等比较rightCtr==leftCtr应该在for循环外检查。
  • 非常感谢!
  • @musefan 是的,刚刚做到了。非常感谢
  • 错误是左大括号和右大括号的数量相同,但它不像}}{{ this.
  • @musefan 是的,刚刚意识到并修复了它哈哈

标签: java


【解决方案1】:

我认为最简单的方法是只保留一个计数,对于一个开括号,它会增加,对于闭括号,它会减少。然后使用以下规则:

  1. 如果计数曾经低于 0,那么它是无效的(即一个从未打开的右括号)
  2. 如果最后计数不为0,则无效(即开括号太多)

考虑到这一点,您的代码将如下所示:

public boolean bracketsMatch(String brackets)
{
    int count = 0;

    for (int i=0; i< brackets.length(); i++)
    {
        char c = brackets.charAt(i);
        if ( c == '{')
        {
           count++;
        }
        else if (c =='}')
        {
            count--;
        }

        // Process the first rule.
        // Check if we have a negative count (i.e. close bracket without a matching opener).
        // If we have a negative then we know the string is invalid, so we can stop processing and return (false) early.
        if (count < 0)
        {
            return false;
        }
    }

    // Process the second rule.
    // If we got this far then we know there are no invalid close brackets, so now we need to just check to make sure we didn't have too many open brackets.
    // Return true if everything matching (i.e. 0), otherwise false.
    return count == 0; 
}

【讨论】:

  • 好的,有道理,但我不明白它如何适用于 }}{{ 之类的情况?谢谢
  • 因为即使它是 }}{{ 也不等于零吗?因为它是-1-1+1+1 ?
  • @CodingBat: 是的,它会等于零……如果我们让它一直到函数的末尾。这就是我们在每个循环中检查负数的原因。在您的示例中,第一个循环 count 将是 -1,这意味着它无效。如果我们得到-1,那么我们会提前退出函数,所以我们永远不会检查总计数,我们基本上会停止处理字符串的其余部分。
  • 好的,我现在知道了,非常感谢,祝您有美好的一天!
【解决方案2】:

Musefan 已经给出了绝妙的答案。这是另一个实现。使用堆栈数据结构。

public static boolean isBracketMatch(String str) {
    Stack<Character> stack = new Stack<>();
    char c;

    for (int i = 0; i < str.length(); i++) {
        c = str.charAt(i);
        if (c == '{')
            stack.push('}');
        else if (c == '}') {
            if (!stack.empty() && stack.peek() == c)
                    stack.pop();
            else
                return false;
        }
    }
    return stack.empty();
}

【讨论】:

  • 这很好,但主要适用于程序还需要处理多种括号的情况,例如( { 和 [.
  • 这个答案是根据 OP 的要求。但是为任何类型的括号实现它并不困难。 :)
猜你喜欢
  • 2016-07-05
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多