题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
List<Integer> num = new ArrayList();
// 注意 hasNext 和 hasNextLine 的区别
if (in.hasNextInt()) {
int a = in.nextInt();
while(in.hasNext()) {
String t = in.nextLine();
if (t.contains("top")) {
if(num.size()==0){
System.out.println("error");
}else{
System.out.println(num.get(num.size() - 1));
}
} else if (t.contains("pop")) {
if(num.size()==0){
System.out.println("error");
}else{
System.out.println(num.get(num.size() - 1));
num.remove(num.size()-1);
}
} else if(t.contains("push")){
Pattern pattern = Pattern.compile("(\\d+)"); // 匹配一个或多个数字
Matcher matcher = pattern.matcher(t);
if (matcher.find()) {
String numberStr = matcher.group(1); // 获取第一个捕获组的内容,即数字字符串
int number = Integer.parseInt(numberStr); // 将字符串转换为整数
num.add(number);
}
}
}
}
}
}
查看11道真题和解析