思路:使用栈来模拟,但是,需要注意到如下几种情
- 可以创建两个栈,一个记录变量,一个记录时间复杂度。如果出现变量名重复,直接认为ERR,如果pop出来的时间复杂度为n,则将当前复杂度减一,最后只记录遍历过程中的最大复杂度。
- 如果某条语句进入不了循环,那么当前命令下的所有命令都失效。
- 如果某条语句出错,则剩下命令都不考虑。
注意:如果一个字符串出现在行末,使用cin.next()时,要在加上一个cin.nextLine(),否则行末的回车符将影响下一次输入。但是,如果是连续的两个两行的cin.next(),则不需要加上cin.nextLine();
代码
String getO(String s, String e) {
if(!s.contentEquals("n") && e.contentEquals("n")) return "n";
else if(s.contentEquals("n") && !e.contentEquals("n")) return "-1";
else if(s.contentEquals("n") && e.contentEquals("n")) return "1";
else {
int si = Integer.parseInt(s);
int ei = Integer.parseInt(e);
if(si <= ei) return "1";
else return "-1";
}
}
boolean fit(String o, int n) {
if(o.charAt(2) == '1') return n == 0;
else return Integer.parseInt(o.substring(4, o.length()-1)) == n;
}
// boolean fit(String)
void test() throws IOException {
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
for(int i = 0; i < n; i++) {
Stack<String> vars = new Stack<>(); //存放变量名
Stack<String> o_stack = new Stack<String>(); //存放复杂度
int line = cin.nextInt();
String y = cin.next();
cin.nextLine();
boolean err = false;
boolean stop = false;
String stop_char = "";
int maxo = 0;
int o = 0;
for(int k = 0; k < line; k++) {
String code = cin.nextLine();
if(err) continue;
if(code.charAt(0) == 'F') {
String[] cons = code.split(" ");
if(vars.contains(cons[1])) { //如果变量冲突
err = true;
} else {
String reso = getO(cons[2], cons[3]);
if(reso == "-1") { //如果此时无法进入循环,记录
stop = true;
stop_char = cons[1];
}
vars.push(cons[1]);
o_stack.push(reso);
if(reso == "n") o++;
if(!stop) maxo = Math.max(maxo, o);
}
} else { // E
//如果多了一个E
if(vars.isEmpty()) err = true;
else {
String top = vars.pop();
String top_o = o_stack.pop();
if(top == stop_char) stop = false;
if(top_o=="n") o--;
}
}
}
if(err || !vars.isEmpty()) {
System.out.println("ERR");
} else {
if(fit(y, maxo)) System.out.println("Yes");
else System.out.println("No");
}
}
}