Skip to content

Commit 0e6896b

Browse files
Raj MhetarRaj Mhetar
Raj Mhetar
authored and
Raj Mhetar
committed
added problem 1106 - Parsing a Boolean String
1 parent deaecbd commit 0e6896b

File tree

4 files changed

+84
-0
lines changed

4 files changed

+84
-0
lines changed

Diff for: .DS_Store

6 KB
Binary file not shown.

Diff for: Cpp/.DS_Store

20 KB
Binary file not shown.

Diff for: Cpp/1106 - Parsing A Boolean Expression/problem.md

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
A boolean expression is an expression that evaluates to either true or false, and it can have the following forms:
2+
3+
1. `'t'`: evaluates to true.
4+
2. `'f'`: evaluates to false.
5+
3. `'!(subExpr)'`: evaluates to the logical NOT of the inner expression `subExpr`.
6+
4. `'&(subExpr1, subExpr2, ..., subExprn)'`: evaluates to the logical AND of the inner expressions `subExpr1, subExpr2, ..., subExprn`, where `n >= 1`.
7+
5. `'|(subExpr1, subExpr2, ..., subExprn)'`: evaluates to the logical OR of the inner expressions `subExpr1, subExpr2, ..., subExprn`, where `n >= 1`.
8+
9+
Given a string `expression` that represents a boolean expression, return its evaluation. It is guaranteed that the expression is valid and follows the rules described above.
10+
11+
---

Diff for: Cpp/1106 - Parsing A Boolean Expression/solution.cpp

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
class Solution
2+
{
3+
public:
4+
char solve(vector<char> &temp, char op)
5+
{
6+
if (op == '!')
7+
{
8+
return temp[0] == 'f' ? 't' : 'f'; // Negate the first element
9+
}
10+
else if (op == '&')
11+
{
12+
for (char &ch : temp)
13+
{
14+
if (ch == 'f')
15+
{
16+
return 'f'; // If any 'f', the result is 'f'
17+
break;
18+
}
19+
}
20+
return 't'; // Otherwise, the result is 't'
21+
}
22+
else if (op == '|')
23+
{
24+
for (char &ch : temp)
25+
{
26+
if (ch == 't')
27+
{
28+
return 't'; // If any 't', the result is 't'
29+
break;
30+
}
31+
}
32+
return 'f'; // Otherwise, the result is 'f'
33+
}
34+
return 'f'; // Default case (shouldn't reach here)
35+
}
36+
37+
bool parseBoolExpr(string exp)
38+
{
39+
stack<char> st;
40+
41+
for (char &ch : exp)
42+
{
43+
if (ch == ',')
44+
{
45+
continue; // Ignore commas
46+
}
47+
else if (ch == ')')
48+
{
49+
vector<char> temp;
50+
51+
// Collect all characters until '('
52+
while (st.top() != '(')
53+
{
54+
temp.push_back(st.top());
55+
st.pop();
56+
}
57+
st.pop(); // Remove the '('
58+
59+
char op = st.top(); // Get the operator ('!', '&', or '|')
60+
st.pop(); // Remove the operator
61+
62+
// Solve the current expression and push the result
63+
st.push(solve(temp, op));
64+
}
65+
else
66+
{
67+
st.push(ch); // Push characters ('t', 'f', operators, '(') onto
68+
// the stack
69+
}
70+
}
71+
return st.top() == 't'; // The final result is at the top of the stack
72+
}
73+
};

0 commit comments

Comments
 (0)