1106.cpp (1226B)
1 class Solution { 2 public: 3 bool parseBoolExpr(const string &expression) const { 4 bool state = false; 5 stack<char> op; 6 7 const auto flush = [&](int &i) { 8 for (int count = 0; i < size(expression); i++) { 9 if (expression[i] == '(') 10 count++; 11 else if (expression[i] == ')' && count-- == 0) 12 break; 13 } 14 op.pop(); 15 }; 16 17 for (int i = 0; i < size(expression); i++) { 18 switch (expression[i]) { 19 case 't': state = true; break; 20 case 'f': state = false; break; 21 case '!': 22 case '&': 23 case '|': op.push(expression[i]); break; 24 case ',': 25 // lazy evaluation 26 switch (op.top()) { 27 case '&': 28 if (!state) flush(i); 29 break; 30 case '|': 31 if (state) flush(i); 32 break; 33 } 34 break; 35 case ')': 36 if (op.top() == '!') state = !state; 37 38 op.pop(); 39 break; 40 } 41 } 42 43 return state; 44 } 45 };