日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

天池 在线编程 布尔表达式求值(栈)

發布時間:2024/7/5 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 天池 在线编程 布尔表达式求值(栈) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

    • 1. 題目
    • 2. 解題

1. 題目

https://tianchi.aliyun.com/oj/245679029019779851/254275128279634588

給定一個字符串代表一個僅包含"true","false","or","and"的布爾表達式。
你的任務是將這個表達式的值求出,返回"true"或"false"。
如果該表達式是錯誤的,則返回"error"。

數據保證表達式中只含有"true",“false”,“or”,"and"四種字符串。
表達式中的元素不會超過10000個。

示例 樣例 1 輸入: "true and false" 輸出: "false"樣例 2 輸入: "true or" 輸出: "error"

2. 解題

  • 先檢查是否是合法表達式,首尾只能是 bool,中間不能有連續的 操作符
  • 在用棧記錄 bool 值,遇到 and 時,當前 bool 與棧頂 bool 操作,再把結果入棧
  • 遇到 or 直接把 bool 值入棧
  • 最后棧內的 bool 全部做 or 運算
class Solution { public:/*** @param expression: a string that representing an expression* @return: the result of the expression*/string evaluation(string &exp) {// write your code hereexp += ' ';string prev, cur;unordered_set<string> s1 = {"true", "false"},s2 = {"or", "and"};for(int i = 0; i < exp.size(); i++) {if(exp[i] != ' ')cur += exp[i];else{if((prev=="" || i==exp.size()-1) && (cur=="and" || cur=="or"))return "error";//首尾是操作符if((s1.count(prev)&&s1.count(cur))||(s2.count(prev)&&s2.count(cur)))return "error";//連續的操作數,或者連續的操作符prev = cur;cur = "";}}stack<bool> stk;prev = cur = "";for(int i = 0; i < exp.size(); i++) {if(exp[i] != ' ')cur += exp[i];else{if(prev=="" || prev=="or")stk.push(cur=="true" ? true : false);else if(prev == "and"){bool tp = stk.top();stk.pop();stk.push(tp&&(cur=="true" ? true : false));}prev = cur;cur = "";}}bool ans = stk.top();stk.pop();while(!stk.empty() && ans==false){ans = ans||stk.top();stk.pop();}return ans ? "true" : "false";} };

50ms C++


我的CSDN博客地址 https://michael.blog.csdn.net/

長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!

總結

以上是生活随笔為你收集整理的天池 在线编程 布尔表达式求值(栈)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。