实现字通配符

 

 

 1 import java.util.*;
 2    
 3 public class Main {
 4     private static boolean match(String matchStr, String str, int matchIdx, int idx) {
 5         if (matchIdx == matchStr.length() && idx == str.length()) {
 6             return true;
 7         }
 8         //str匹配到最后一个字符了,matchIdx后面还有多个*的情况
 9         if (idx == str.length() && matchIdx < matchStr.length() && matchStr.charAt(matchIdx) == '*') {
10            return match(matchStr, str, matchIdx + 1, idx);
11         }
12         if (matchIdx >= matchStr.length() || idx >= str.length()) {
13             return false;
14         }
15         //匹配中出现了不同的字符
16         if (matchStr.charAt(matchIdx) != '*' && matchStr.charAt(matchIdx) != str.charAt(idx)) {
17             return false;
18         }
19         boolean flag = false;
20         //匹配中对*处理,*能表示多个字符,所以idx + 1,直到到达str的最后一个字符
21         if (matchStr.charAt(matchIdx) == '*') {
22             flag = match(matchStr, str, matchIdx + 1, idx) || match(matchStr, str, matchIdx, idx + 1);
23         }
24         //匹配中两个字符串的字符相同的情况,用与或保证可以从false变回true
25         if (matchStr.charAt(matchIdx) == str.charAt(idx)) {
26             flag |= match(matchStr, str, matchIdx + 1, idx + 1);
27         }
28         return flag;
29     }
30    
31     private static List<Integer[]> getMatchPosAndLen(String matchStr, String str) {
32         List<Integer[]> ans = new ArrayList<>();
33          //找到头尾都相等的情况
34         for (int i = 0; i < str.length(); ++i) {
35             //保证第一个字符相同
36             if (matchStr.charAt(0) != '*' && matchStr.charAt(0) != str.charAt(i)) {
37                 continue;
38             }
39             
40             for (int j = i; j < str.length(); ++j) {
41                 //保证最后一个字符相同
42                 if (matchStr.charAt(matchStr.length() - 1) != '*' && matchStr.charAt(matchStr.length() - 1) != str.charAt(j)) {
43                     continue;
44                 }
45                 if (match(matchStr, str.substring(i, j + 1), 0, 0)) {
46                     ans.add(new Integer[]{i, j - i + 1});
47                 }
48             }
49         }
50         if (ans.size() == 0) {
51             ans.add(new Integer[]{-1, 0});
52         }
53         return ans;
54     }
55    
56     public static void main(String[] args) {
57         Scanner in = new Scanner(System.in);
58          String matchStr = in.next();
59         String str = in.next();
60         List<Integer[]> list = getMatchPosAndLen(matchStr, str);
61         for (Integer[] arr : list) {
62             System.out.println(arr[0] + " " + arr[1]);
63         }
64    
65     }
66 }

猜你喜欢

转载自www.cnblogs.com/gy7777777/p/13190154.html