給出一個布爾表達式的字符串,比如:true or false and false,表達式只包含true,false,and和or,現在要對這個表達式進行布爾求值,計算結果為真時輸出true、為假時輸出false,不合法的表達時輸出error(比如:true true)。表達式求值是注意and 的優先級比 or 要高,比如:true or false and false,等價於 true or (false and false),計算結果是 true。
輸入描述:
輸入第一行包含布爾表達式字符串s,s只包含true、false、and、or幾個單詞(不會出現其它的任何單詞),且單詞之間用空格分隔。 (1 ≤ |s| ≤ 103).
輸出描述:
輸出true、false或error,true表示布爾表達式計算為真,false表示布爾表達式計算為假,error表示一個不合法的表達式。
輸入例子1:
and
輸出例子1:
error
輸入例子2:
true and false
輸出例子2:
false
輸入例子3:
true or false and false
輸出例子3:
true
思路:
剛開始思路挺混亂的,但是后來發現這道題是由一道題改編過來的,原題應該就是算數表達式求值這道題。
Code:
#include<iostream> #include<string> #include<stack> using namespace std; int main() { string str; getline(cin, str); int pos; stack<bool> var; stack<string> op; string temp; str += " "; while(str.find(' ') != string::npos) { pos = str.find(' '); temp = str.substr(0, pos); if (temp == "true") var.push(true); else if (temp == "false") var.push(false); else op.push(temp); str = str.substr(pos+1); } if (op.size()+1 != var.size()) { cout << "error" << endl; } else { if (var.size() == 1) { temp = var.top() == true ? "true" : "false"; cout << temp << endl; } else { bool ans, b1, b2; bool haveTrue = false; b1 = var.top(); var.pop(); b2 = var.top(); var.pop(); string s = op.top(); op.pop(); while (var.size() >= 1) { if (s == "and") { ans = b1 && b2; var.push(ans); } else { if (b1 == true) haveTrue = true; var.push(b2); } b1 = var.top(); var.pop(); b2 = var.top(); var.pop(); s = op.top(); op.pop(); } if (s == "and") { temp = (b1 && b2) == true ? "true" : "false"; cout << temp << endl; } else { temp = (b1 || b2) == true ? "true" : "false"; cout << temp << endl; } } } return 0; }