牛客网刷的一道搜狗笔试题
题目不难,就是自己对java还不够了解,字符串里边的方法还不够熟悉
题目如下:
在搜索引擎后端服务中,需要对恶意的抓取进行限制,其中的一个环节即对访问IP进行限制。请设计一个IP过滤器,实现对访问的IP限制的功能。对IP的限制数据有三种格式:
1.全IP:如222.205.58.16
2.前面带 *:如 *.58.16
3.后面带 *:如 222.205.58.*
带 * 的表示匹配到任意的IP段均可,且 * 可以代表多个ip段,且 * 只能出现在开头或者结尾。
现给出若干条需要过滤的规则,以及若干输入的IP,你需要输出这若干条IP是否会被过滤
输入描述:
输入的第一行是过滤规则的条数N和需要过滤的IP数量M,之后的N行为IP的过滤规则且均合法,再之后的M行为需要进行判断是否被过滤的IP。其中N<100,M<50。
输出描述:
0:该条IP不会被过滤 1:该条IP会被过滤 总共M条需要判断的IP需要以空格作为区分
输入例子1:
5 3 222.205.58.16 *.58.16 222.205.58.* *.16 224.* 222.205.58.17 222.205.59.19 223.205.59.16
输出例子1:
1 0 1
例子说明1:
由于222.205.58.17这个IP匹配到222.205.58.*这条过滤规则,222.205.59.19没有匹配到任何过滤规则,223.205.59.16匹配到*.16这条过滤规则,所以输出1 0 1
这个题不用往麻烦里边想,根据题目可以已知 * 只能出现在开头或者结尾,所以这个题可以直接用java里的startsWith() 和endsWith()方法直接匹配字符串就可以,暴力搜索
定义和用法
startsWith() 方法用于检测字符串是否以指定的子字符串开始。
如果是以指定的子字符串开头返回 true,否则 false。
startsWith() 方法对大小写敏感。
endsWith()是用于检测字符串是否以指定的子字符串结束
语法
public boolean endsWith(String suffix)
public boolean startsWith(String suffix)
题解:
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int M = in.nextInt();
String[] str = new String[N];
String[] st = new String [M];
for (int i = 0; i < N; i++) {
str[i] = in.next();
}
for (int i = 0; i < M; i++) {
st[i] = in.next();
}
for (int i = 0; i < st.length; i++) {
boolean flag = true;
String t = "";
for (int j = 0; j < str.length; j++) {
if(str[j].charAt(0) == '*'){
t = str[j].replace("*", "");
if(st[i].endsWith(t)){
System.out.println(1 + " ");
flag = false;
break;
}
}else if(str[j].charAt(str[j].length()-1) == '*'){
t = str[j].replace("*", "");
if(st[i].startsWith(t)){
System.out.println(1 + " ");
flag = false;
break;
}
}else{
if(str[j].equals(st[i])){
System.out.println(1 + " ");
flag = false;
break;
}
}
}
if(flag){
System.out.println(0 + " ");
}
}
}
}