1106. 解析布尔表达式

1106. 解析布尔表达式

题解:每个小括号都可以优先递归计算,dfs

class Solution {
    int index;
    char[] ch;
     public boolean parseBoolExpr(String expression) {
        ch = expression.toCharArray();
        index = 0;
        return dfs();
    }

    public boolean dfs() {
        if (ch[index] == 'f') {
            index++;
            return false;
        }
        if (ch[index] == 't') {
            index++;
            return true;
        }
        // 如果是操作符,需要跳过'('
        char op = ch[index];
        index += 2;

        // 如果是 ! or & 初始化为true
        boolean res = true;
        // 如果是 | 初始化为false
        if (op == '|') res = false;

        while(ch[index] != ')') {
            // ',' 跳过
            if (ch[index] == ',') {
                index ++;
            } else {
                boolean nextBool = dfs();
                // '|' 直接或运算
                if (op == '|') {
                    res = res | nextBool;
                } else {
                // '&' or '!' 直接与运算,  '!': true & !(false) = true , true & !(true) = false
                    res = res & nextBool;
                }
            }
        }
        // 跳过')'
        index ++;
        // 取反
        if (op == '!') {
            res = !res;
        }
        return res;
    }
}
posted @ 2022-11-05 12:04  Eiffelzero  阅读(34)  评论(0)    收藏  举报