-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 1106. Parsing A Boolean Expression
- Loading branch information
1 parent
225dd30
commit ae90f7b
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
class Solution { | ||
public: | ||
bool parseBoolExpr(string expression) { | ||
|
||
stack<char> st, op; | ||
|
||
for(auto & it: expression){ | ||
|
||
if(it == '&' || it == '|' || it == '!'){ | ||
op.push(it); | ||
} | ||
else if(it == ')'){ | ||
|
||
int f = 0, t = 0; | ||
while(st.top() != '('){ | ||
char ch = st.top(); | ||
if(ch == 'f') f++; | ||
if(ch == 't') t++; | ||
st.pop(); | ||
} | ||
|
||
st.pop(); | ||
|
||
if(op.top() == '&'){ | ||
if(f == 0) st.push('t'); | ||
else st.push('f'); | ||
} | ||
else if(op.top() == '|'){ | ||
if(t > 0) st.push('t'); | ||
else st.push('f'); | ||
} | ||
else{ | ||
if(f == 0) st.push('f'); | ||
else st.push('t'); | ||
} | ||
op.pop(); | ||
} | ||
else{ | ||
st.push(it); | ||
} | ||
} | ||
|
||
return st.top() == 'f' ? false : true; | ||
} | ||
}; |