AcWing 3259. URL映射 Java 炸裂代码 不断调试 split
原题链接
中等
作者:
西红柿炒番茄_7
,
2024-11-28 20:42:43
,
所有人可见
,
阅读 1
Java 代码
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
static ArrayList<String> regs = new ArrayList<String>();
static ArrayList<String> patterns = new ArrayList<String>();
static ArrayList<String> arguments = new ArrayList<String>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
while (n-- > 0) {
String reg = sc.next();
String value = sc.next();
regs.add(reg);
patterns.add(value);
}
while (m-- > 0) {
String t = sc.next();
int match = match(t);
if (match != -1) {
System.out.print(patterns.get(match) + " ");
for (int i = 0; i < arguments.size(); i++) {
System.out.print(arguments.get(i) + " ");
}
System.out.println();
} else
System.out.println(404);
}
}
private static int match(String t) {
if (t.contains("?")) {
return -1;
}
String[] t_split = t.split("/");
for (String reg : regs) {
arguments.clear();
//解析
String[] reg_split = reg.split("/");
boolean pat = true;
//额外一个 如果 末尾有 /
if (reg.endsWith("/") && !t.endsWith("/") || !reg.endsWith("/") && t.endsWith("/") && !reg.endsWith("<path>")) {
continue;
}
if (!reg.endsWith("<path>") && t_split.length != reg_split.length){
continue;
}
for (int i = 0; i < reg_split.length; i++) {
if (!pat) break;
if (i >= t_split.length) {
pat = false;
break;
}
if (t_split[i].equals("") && reg_split[i].equals("")) {
continue;
}
String reg_segment = reg_split[i];
String t_segment = t_split[i];
if (reg_segment.startsWith("<")) {
reg_segment = reg_segment.substring(1, reg_segment.length() - 1);
if (reg_segment.equals("int")) {
if (!isNum(t_segment)) {
pat = false;
break;
}
arguments.add(Integer.valueOf(t_segment).toString());
} else if (reg_segment.equals("str")) {
//存储一段
arguments.add(t_segment);
} else if (reg_segment.equals("path")) {
//存储i以及剩余所有t_split
String left = "";
for (int j = i; j < t_split.length; j++) {
left += t_split[j];
if (j != t_split.length - 1) {
left += "/";
}
if (j == t_split.length - 1 && t.endsWith("/"))
left += "/";
}
arguments.add(left);
pat = true;
break;
}
} else {
if (!reg_segment.equals(t_segment)) {
pat = false;
break;
}
}
}
if (pat) {
//找到该reg
int i = regs.indexOf(reg);
return i;
}
}
return -1;
}
public static boolean isNum(String str) {
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) < '0' || str.charAt(i) > '9')
return false;
}
return true;
}
}