java 实现表达式求解
问题了解等价表达式
理论参考表达式求值
java 实现
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.Stack;
public class computer {
static Stack s1 = null;
static Stack s2 = null;
public static void main(String[] args) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Scanner scanner = new Scanner(System.in);
int N=1000;
String str1 = scanner.nextLine();
long[] a = new long[N];
for (int i=0; i<N; i++) {
s1 = new Stack<>();
s2 = new Stack<>();
String str2 =str1.replace("a", "" + i);
zhtohou(str2);
a[i] = (long) s1.pop()%1000000007;
}
int n = scanner.nextInt();
scanner.nextLine();
String[] strs = new String[n];
for (int i = 0; i < n; i++) {
strs[i] = scanner.nextLine();
}
boolean jug = true;
for (int j=0; j<n; j++) {
jug = true;
str1 = strs[j];
for (int i=0; i<N; i++) {
s1 = new Stack<>();
s2 = new Stack<>();
String str2 =str1.replace("a", "" + i);
zhtohou(str2);
if ( a[i] != (long) s1.pop()%1000000007){
jug = false;
break;
}
}
if (jug) System.out.print((char)('A'+j));
}
}
public static long mycom(long a, long b, char ch) {
if (ch=='+')return a+b;
else if (ch=='-')return a-b;
else if (ch=='*')return a*b;
else if (ch=='^')return (long)Math.pow(a,b);
else return a/b;
}
public static boolean isNumber(char c) {
if (c>='0' && c<='9') return true;
return false;
}
private static void zhtohou(String str) {
char[] chs = str.toCharArray();
for (int i=0; i<str.length(); i++) {
if (isNumber(chs[i])) {
if (chs[i] == ' ')continue;
String ss = "";
while ( i<chs.length && isNumber(chs[i]) ) {
ss += str.charAt(i);
i++;
}
long a = Integer.parseInt(ss);
s1.add(a);
i--;
continue;
}
if (chs[i] == '(') {
s2.add(chs[i]);
continue;
}
if (chs[i] == ')') {
while (!s2.isEmpty() && (char)s2.peek()!='(') {
char ch = (char)s2.pop();
long a = (long)s1.pop();
long b = (long)s1.pop();
s1.add(mycom(b,a,ch));
}
s2.pop();
continue;
}
if (chs[i]=='-' || chs[i]=='+') {
while (!s2.isEmpty() && (char)s2.peek()!='(') {
char ch = (char)s2.pop();
long a = (long)s1.pop();
long b = (long)s1.pop();
s1.add(mycom(b,a,ch));
}
s2.add(chs[i]);
continue;
}
if (chs[i]=='*' || chs[i]=='/') {
while (!s2.isEmpty() && ((char)s2.peek()=='*' || (char)s2.peek()=='/' || (char)s2.peek()=='^')) {
char ch = (char)s2.pop();
long a = (long)s1.pop();
long b = (long)s1.pop();
s1.add(mycom(b,a,ch));
}
s2.add(chs[i]);
continue;
}
if (chs[i]=='^'){
s2.add(chs[i]);
continue;
}
}
while (!s2.isEmpty()) {
char ch = (char)s2.pop();
long a = (long)s1.pop();
long b = (long)s1.pop();
s1.add(mycom(b,a,ch));
}
}
}