public class Parse{ public static void main(String[] args) throws Exception{ System.out.print(parse("true&&(true)&&(true&&true&&(true&&false||true||(true||false)))")); System.out.println(true&&(true)&&(true&&true&&(true&&false||true||(true||false)))); System.out.print(parse("true&&(true)&&(true&&true&&(true||(true||false)))")); System.out.println(true&&(true)&&(true&&true&&(true||(true||false)))); System.out.print(parse("((true&&false||false&&(true||false)))")); System.out.println(((true&&false||false&&(true||false)))); } public static boolean parse(String s){ s = s.replace("true","1"); s = s.replace("false","0"); s = s.replace("||","|"); s = s.replace("&&","&"); int head = 0; boolean curBool = true; char operator = '&'; while(head < s.length()){ if(s.charAt(head) == '1') curBool = judge(curBool,true,operator); else if(s.charAt(head) == '0') curBool = judge(curBool,false,operator); else if(s.charAt(head) == '('){ int end = getEnd(s,head); curBool = judge(curBool, parse(s.substring(head + 1, end)),operator); head = end; } else throw new RuntimeException("format error "+s); if(++head >= s.length()) { return curBool; } if(s.charAt(head) == '|') { if(curBool) { // 如果当前为true,且下个操作是“或”,则返回true return true; } operator = '|'; } else if(s.charAt(head) == '&') operator = '&'; else throw new RuntimeException("format error "+s); head ++; } return curBool; } public static int getEnd(String s,int start){ int count = 0; while (start < s.length()) { if (s.charAt(start) == ')' && count == 1) { return start; } else if (s.charAt(start) == '(') count++; else if (s.charAt(start) == ')') count--; start++; } throw new RuntimeException(") not match"); } public static boolean judge(boolean lastBool, boolean curBool, char oper){ return oper == '|'? (lastBool || curBool) : (lastBool && curBool); } }