【leetcode】1106. Parsing A Boolean Expression

题目如下:

Return the result of evaluating a given boolean expression, represented as a string.

An expression can either be:

  • "t", evaluating to True;
  • "f", evaluating to False;
  • "!(expr)", evaluating to the logical NOT of the inner expression expr;
  • "&(expr1,expr2,...)", evaluating to the logical AND of 2 or more inner expressions expr1, expr2, ...;
  • "|(expr1,expr2,...)", evaluating to the logical OR of 2 or more inner expressions expr1, expr2, ...

Example 1:

Input: expression = "!(f)"
Output: true

Example 2:

Input: expression = "|(f,t)"
Output: true

Example 3:

Input: expression = "&(t,f)"
Output: false

Example 4:

Input: expression = "|(&(t,f,t),!(t))"
Output: false

Constraints:

  • 1 <= expression.length <= 20000
  • expression[i] consists of characters in {‘(‘, ‘)‘, ‘&‘, ‘|‘, ‘!‘, ‘t‘, ‘f‘, ‘,‘}.
  • expression is a valid expression representing a boolean, as given in the description.

解题思路:本题和表达式运算的题目相似。遍历expression并将每一个字符依次入栈,如果遇到‘)‘,则找出离栈顶最近的‘(‘,计算出括号之内的表达式的值并将该值入栈,直到expression遍历完成为止。

代码如下:

class Solution(object):
    def parseBoolExpr(self, expression):
        """
        :type expression: str
        :rtype: bool
        """
        stack = []
        expression = expression.replace(‘t‘,‘1‘)
        expression = expression.replace(‘f‘, ‘0‘)
        ex = list(expression)
        while len(ex) > 0:
            char = ex.pop(0)
            if char != ‘)‘:
                stack.append(char)
                continue
            ts = ‘‘
            while len(stack) > 0:
                item = stack.pop(-1)
                if item == ‘(‘:
                    break
                ts += item
            ts_list = ts.split(‘,‘)
            and_or = stack.pop(-1)
            if and_or == ‘!‘:
                stack.append(‘1‘ if ts_list[0] == ‘0‘ else ‘0‘ )
            elif and_or == ‘|‘:
                stack.append(‘1‘ if ‘1‘ in ts_list else ‘0‘)
            else:
                stack.append(‘0‘ if ‘0‘ in ts_list else ‘1‘)
        return stack[0] == ‘1‘

原文地址:https://www.cnblogs.com/seyjs/p/11139786.html

时间: 2025-01-09 11:39:40

【leetcode】1106. Parsing A Boolean Expression的相关文章

【leetcode】Word Break

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, givens = "leetcode",dict = ["leet", "code"]. Return true because &

【LeetCode】Climbing Stairs

Set集合的配置 数据表的创建:表关系一个员工拥有多个身份 create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id) ); create table CERTIFICATE ( id INT NOT NULL aut

【LeetCode】Validate Binary Search Tree

Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys

【LeetCode】Jump Game II

Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps

【leetcode】com/problems/surrounded-regions/

dfs 栈溢出,bfs超时,用dfs非递归就不溢出了,前后写了1一个星期class node { int i; int j; public node(int i1,int j1) { i=i1; j=j1; } } public class Solution { public void solve(char[][] board) { int len1=board.length; if(len1<=0)return; int len2=board[0].length; if(len1<=2||l

【LeetCode】Word Search II 解题报告

[题目] Given a 2D board and a list of words from the dictionary, find all words in the board. Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The sa

【LeetCode】103. Binary Tree Zigzag Level Order Traversal 解题报告

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51524241 Subject 出处:https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to ri

【LeetCode】Subsets II 解题报告

[题目] Given a collection of integers that might contain duplicates, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,2], a solutio

【leetcode】Generate Parentheses

题目: 给定整数n,返回n对匹配的小括号字符串数组. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" 分析: 这种问题的模式是:1)问题的解有多个 ,2)每个解都是由多个有效的 "步骤" 组成的,3)变更以有解的某个或某些"步骤"