分析字符串形式的布尔表达式,求取其对应的值
用字符‘T’代表true,字符‘F代表false,&? |? !对应与或非
源码如下:
import java.util.ArrayList;
import java.util.List;
public class BoolString {
private static void split(String value,List<Character> signs, List<String> parts) {
int tier = 0;
int start = 0;
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (c == '(') {
if (tier == 0) start = i + 1;
tier++;
}
if (c == ')') {
tier--;
if (tier == 0) {
parts.add(value.substring(start, i));
start = i + 1;
}
}
if (tier == 0) {
if (c == '!') {
signs.add(c);
start++;
}
if (c == '&' || c == '|') {
signs.add(c);
if (start == i) {
start = i + 1;
continue;
}
parts.add(value.substring(start, i));
start += 2;
}
}
}
if (start < value.length()) parts.add(value.substring(start));
}
public static boolean parse(String the) {
boolean root = false;
List<Character> signs =new ArrayList<>();
List<String> parts = new ArrayList<>();
if (the.length() == 1) root = true;
else {
split(the,signs,parts);
}
if (!root) {
boolean fast = parse(parts.get(0));
boolean used = false;
for (char c : signs) {
if (c == '&' && !fast) {
used = true;
break;
}
if (c == '|' && fast) {
used = true;
break;
}
}
if (used) {
for (char c : signs) {
if (c == '!') {
fast = !fast;
} else return fast;
}
}
int p = parts.size() - 1;
boolean now = parse(parts.get(parts.size() - 1));
for (int i = signs.size() - 1; i >= 0; i--) {
if (p - 1 >= 0) {
Character sign = signs.get(i);
boolean b1 = parse(parts.get(p));
boolean b2 = parse(parts.get(p - 1));
while (true){
if (sign == '!') {
b1 = !b1;
if (i - 1 < 0) {
return b1;
}
i -= 1;
sign = signs.get(i);
}else break;
}
if (sign == '&') {
now = b1 && b2;
continue;
}
if (sign == '|') {
now = b1 || b2;
continue;
}
}
now = !now;
}
return now;
} else return the.equals("T");
}
}
转载须注明出处
|