题解 | #字符串通配符#
字符串通配符
https://www.nowcoder.com/practice/43072d50a6eb44d2a6c816a283b02036
代码写的有点乱 但是想出来分享一下做题心得和思路,和以往做题方式不同,因为条件众多,我没有想之前全部想明白再写,
1.我也感觉每次直接想明白解题思路再写并不是容易的事,大部分都是写着写着就出来思路了。
2.因为只有两种结果,所以我在遍历的时候想着 我把所有为 false的找出来,最后在返回一个ture就可以。
3.初步写完因为条件很多,说实在的你让我自己完整复述一下 我都复述不出来。但是我直接提交。看那些没有通过,然后改进 (这样确实很快可以ac这道题目)
4.后来我发现 判断*的地方有两种情况,所以直接想到了递归。因此我又提取了一个方法,做递归。
5.然后缝缝补补 就AC出来了
觉得以后都可以通过这种方式做题,不需要全部想明白有没有漏掉那些边界值,只需要,通过用例来补充边界值就可以。
就是不知道考试的时候可不可以看到测试用例。
import java.util.*;
import java.text.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
char[] a = in.nextLine().toLowerCase().toCharArray();
char[] b = in.nextLine().toLowerCase().toCharArray();
// 写入栈
Stack<Character> stack = new Stack<Character>();
for (int i = b.length - 1 ; i >= 0 ; i --) {
stack.push(b[i]);
}
System.out.println( faction(a, 0, stack) );
}
}
public static boolean faction(char[] a, int index, Stack<Character> stack) {
for (int i = index ; i < a.length ; i ++ ) {
if (!stack.isEmpty()) {
if (a[i] == stack.peek()) {
stack.pop();
continue;
} else if (a[i] == '?') {
stack.pop();
continue;
} else if (a[i] == '*' &&
(Character.isDigit(stack.peek()) ||
('a' <= stack.peek() && 'z' >= stack.peek() ))) {
Stack test1 = (Stack<Character>) stack.clone();
Stack test2 = (Stack<Character>) stack.clone();
test2.pop();
if ( faction(a, i + 1, test1) || faction(a, i + 1, test2) ) {
return true;
} else if (a[i] == '*' && i == a.length-1) {
return true;
} else if (a[i] == '*') {
continue;
} else {
return false;
}
} else {
return false;
}
} else {
if (a[i] == '?' || a[i] == '*') {
continue;
} else {
return false;
}
}
}
if (stack.isEmpty()) {
return true;
} else {
return false;
}
}
}
#22届实习#import java.text.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
char[] a = in.nextLine().toLowerCase().toCharArray();
char[] b = in.nextLine().toLowerCase().toCharArray();
// 写入栈
Stack<Character> stack = new Stack<Character>();
for (int i = b.length - 1 ; i >= 0 ; i --) {
stack.push(b[i]);
}
System.out.println( faction(a, 0, stack) );
}
}
public static boolean faction(char[] a, int index, Stack<Character> stack) {
for (int i = index ; i < a.length ; i ++ ) {
if (!stack.isEmpty()) {
if (a[i] == stack.peek()) {
stack.pop();
continue;
} else if (a[i] == '?') {
stack.pop();
continue;
} else if (a[i] == '*' &&
(Character.isDigit(stack.peek()) ||
('a' <= stack.peek() && 'z' >= stack.peek() ))) {
Stack test1 = (Stack<Character>) stack.clone();
Stack test2 = (Stack<Character>) stack.clone();
test2.pop();
if ( faction(a, i + 1, test1) || faction(a, i + 1, test2) ) {
return true;
} else if (a[i] == '*' && i == a.length-1) {
return true;
} else if (a[i] == '*') {
continue;
} else {
return false;
}
} else {
return false;
}
} else {
if (a[i] == '?' || a[i] == '*') {
continue;
} else {
return false;
}
}
}
if (stack.isEmpty()) {
return true;
} else {
return false;
}
}
}