第1106题
总的就是栈+递归,初始化两个栈,一个符号栈,一个字符栈
遇到(就进行递归,递归到)结束,然后进行计算,将递归的总结果压入字符栈
最后字符栈只会有一个字符。就是最后的结果
class Solution {
Stack<Character> symbolStack = new Stack<>();
Stack<Character> charStack = new Stack<>();
int index = 0;
public boolean parseBoolExpr(String str) {
dfs(str);
Character pop = charStack.pop();
if(pop == 't'){
return true;
}else{
return false;
}
}
public Character dfs(String str){
int count = 0;
for(; index < str.length(); index++){
char c = str.charAt(index);
if(c == ','){
continue;
}
if(c == '|' || c =='&' || c == '!'){
symbolStack.add(c);
continue;
}
if(c == '('){
index++;
charStack.add(dfs(str));
count++;
continue;
}
if(c == ')'){
return doCalculate(count);
}
if(c == 't' || c == 'f'){
charStack.add(c);
count++;
}
}
return null;
}
public Character doCalculate(int count){
Character symbol = symbolStack.pop();
Set<Character> set = new HashSet<>();
for(int i = 0; i < count; i++){
set.add(charStack.pop());
}
if(symbol == '!'){
if(set.contains('t')){
return 'f';
}else{
return 't';
}
}
if(symbol == '|'){
if(set.contains('t')){
return 't';
}else{
return 'f';
}
}
if(set.contains('f')){
return 'f';
}else{
return 't';
}
}
}
结果