Evaluator Expression:如何知道输入是否错误

Evaluator Expression: How to know if the input is wrong

我正在解决下一个技术问题 (Q1):http://blog.sdeskills.com/qotd-2016-oct-17-resistance-is-futile/

快完成了,只有一项任务待处理。评估输入是否平衡。检查括号是否有序,这已经完成,但不是评估标记。

In a given sub-network cannot have a mix of series / parallel connections, so (500+200|300) is not allowed.

这是我当前的代码:https://repl.it/EC3i/2知道如何将前面的表达式评估为错误吗?

试试这个。此代码检查运算符 sereis 以及平衡括号。

static boolean isBalanced(String s) {
    Deque<Character> operators = new LinkedList<>();
    operators.push('#');
    for (int i = 0; i < s.length(); ++i) {
        if (operators.isEmpty()) return false;
        char ch = s.charAt(i);
        switch (ch) {
        case '(': operators.push('#'); break;
        case ')': operators.pop(); break;
        case '+':
            switch (operators.peek()) {
            case '#': operators.pop(); operators.push(ch); break;
            case '+': break;
            default: return false;
            }
            break;
        case '|':
            switch (operators.peek()) {
            case '#': operators.pop(); operators.push(ch); break;
            case '|': break;
            default: return false;
            }
            break;
        }
    }
    return operators.size() == 1;
}

和 JUnit 测试代码。

@Test
public void testIsBalanced() {
    assertTrue(isBalanced("(2)"));
    assertTrue(isBalanced("(2+3+3)"));
    assertTrue(isBalanced("2+3+3"));
    assertTrue(isBalanced("2+(4|5|5)+3"));
    assertTrue(isBalanced("2+(4|(2+3+4)|5)+3"));
    assertTrue(isBalanced("(2)+3()"));
    assertFalse(isBalanced("(2"));
    assertFalse(isBalanced("(2))"));
    assertFalse(isBalanced("((2)"));
    assertFalse(isBalanced("2|3+3"));
    assertFalse(isBalanced("2+(4|5+5)+3"));
    assertFalse(isBalanced("2+3|3"));
}