在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Return the result of evaluating a given boolean An expression can either be:
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:
给你一个以字符串形式表述的 布尔表达式(boolean) 有效的表达式需遵循以下约定:
示例 1: 输入:expression = "!(f)" 输出:true 示例 2: 输入:expression = "|(f,t)" 输出:true 示例 3: 输入:expression = "&(t,f)" 输出:false 示例 4: 输入:expression = "|(&(t,f,t),!(t))" 输出:false 提示:
Runtime: 32 ms
Memory Usage: 20.8 MB
1 class Solution { 2 func parseBoolExpr(_ expression: String) -> Bool { 3 var op:[Character] = [Character]() 4 var num:[Int] = [Int]() 5 for ch in expression 6 { 7 if ch == "t" {num.append(1)} 8 else if ch == "f" {num.append(0)} 9 else if (ch == "|") || (ch == "&") || (ch == "!") {op.append(ch)} 10 else if ch == "(" {num.append(-1)} 11 else if ch == "," {continue} 12 else if ch == ")" 13 { 14 var ans:Int = num.popLast()! 15 let p:Character = op.popLast()! 16 while(num.last! != -1) 17 { 18 let a:Int = num.popLast()! 19 if p == "&" {ans = ans & a} 20 else if p == "|" {ans = ans | a} 21 } 22 num.popLast() 23 if p == "!" {ans = 1 - ans} 24 num.append(ans) 25 } 26 } 27 if num.last! == 1 28 { 29 return true 30 } 31 return false 32 } 33 }
72ms
1 class Solution { 2 var expressions : [Character] = ["&","|","!"] 3 var bools : [Character] = ["t","f"] 4 func parseBoolExpr(_ expression: String) -> Bool { 5 var stack : String = "" 6 let expression = Array(expression) 7 8 _ = true 9 var currentBools = [Character]() 10 for i in 0..<expression.count { 11 12 if expression[i] == ")" { 13 while let head = stack.popLast(), head != "(" { 14 if head == "t" || head == "f" { 15 currentBools.append(head) 16 } 17 } 18 if let op = stack.popLast() { 19 if op == "&" { 20 stack.append(evaluateAND(currentBools)) 21 currentBools.removeAll() 22 } else if op == "|" { 23 stack.append(evaluateOR(currentBools)) 24 currentBools.removeAll() 25 } else if op == "!" { 26 stack.append(evaluateNot(currentBools.first!)) 27 currentBools.removeAll() 28 } 29 continue 30 } 31 } 32 if bools.contains(expression[i]) { 33 currentBools.append(expression[i]) 34 continue 35 } 36 37 stack.append(expression[i]) 38 } 39 if stack.popLast() == "t" {return true} 40 return false 41 } 42 43 func evaluateOR (_ input: [Character]) -> Character { 44 if input.contains("t") {return "t"} 45 return "f" 46 } 47 48 func evaluateAND (_ input: [Character]) -> Character { 49 if input.contains("f") {return "f"} 50 return "t" 51 } 52 53 func evaluateNot(_ input: Character) -> Character { 54 if input == ("f") {return "t"} 55 return "f" 56 } 57 }
|
请发表评论