一、
二、代码
水平有限,本来是想照着80分写的(圆括号不可以出现嵌套),但结果只得了70分,如果有大神能看出其中的问题,请您不吝指出。
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Stack;
public class Main {
static void count(String s,Map map){
Stack stack = new Stack<String>();
int times = 1;//前面的系数
int kuo = 0;//栈中左括号数量
for(int j=0;j<s.length();j++){
char c = s.charAt(j);
if(c=='('){
kuo++;
stack.push(c);
}
if(c >= 65 && c <= 90)//大写字母
stack.push(c);
if(c >= 97 && c <= 122){//小写字母
String temp = ""+stack.pop();
temp = temp+c;
stack.push(temp);
}
if(c >= 48 && c <= 57){//是数字
if(kuo > 0){
stack.push(c-48);
}
else if(stack.empty()){//元素前面的数字
//这个数有可能不止一位
String temp =""+(c-48);
while(j+1<s.length() && s.charAt(j+1) >= 48 && s.charAt(j+1) <= 57){
temp = temp + (s.charAt(j+1)-48);
j++;
}
times = Integer.parseInt(temp);
}else{//元素后面的数字
String key = ""+stack.pop();
String temp = ""+(c-48);
while(j+1<s.length() && s.charAt(j+1) >= 48 && s.charAt(j+1) <= 57){
temp = temp + (s.charAt(j+1)-48);
j++;
}
int value = times * Integer.parseInt(temp);
if(map.containsKey(key))
map.put(key,(Integer)map.get(key)+value);
else
map.put(key, value);
}
}
if(c == '+'){//碰到+,把栈里剩余的元素都计算一下,加到map里
while(!stack.empty()){
String temp = ""+stack.pop();
if(map.containsKey(temp))
map.put(temp,(Integer)map.get(temp)+times);
else
map.put(temp, times);
}
times=1;
}
if(c == ')'){
//拿到括号后面那个数字(如果有的话)
int value = times;
if(j+1<s.length() && s.charAt(j+1) >= 48 && s.charAt(j+1) <= 57){
String temp = ""+s.charAt(j+1);
j++;
while(j+1<s.length() && s.charAt(j+1) >= 48 && s.charAt(j+1) <= 57){
temp = temp + (s.charAt(j+1)-48);
j++;
}
value = times * Integer.parseInt(temp);
}
int jiao = 1;//指下角标
//直到'('
String key = ""+stack.pop();
while( !key.equals("(")){
if(key.length()==1 && key.charAt(0)>=48 && key.charAt(0)<=57){
jiao = key.charAt(0)-48;
}else{
if(map.containsKey(key)){
map.put(key,(Integer)map.get(key)+(jiao*value));
}
else
map.put(key, (jiao*value));
jiao=1;
}
key = ""+stack.pop();
}
kuo--;
}
}
//把栈中剩余的元素处理一下
while(!stack.empty()){
String temp = ""+stack.pop();
if(map.containsKey(temp))
map.put(temp,(Integer)map.get(temp)+times);
else
map.put(temp, times);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
for(int i=0;i<n;i++){
String s = sc.next();
String left = s.split("=")[0];
String right = s.split("=")[1];
Map map_left = new HashMap<String, Integer>();
Map map_right = new HashMap<String, Integer>();
count(left,map_left);
count(right,map_right);
if(map_left.equals(map_right))
System.out.println("Y");
else
System.out.println("N");
}
}
}