/ wildcard_pattern_matching / wildcard_pattern_matching.java
wildcard_pattern_matching.java
 1  import java.util.Scanner; 
 2  
 3  public class wildcard_pattern_matching {
 4      public static boolean isMatch(String str, String pattern) {
 5          int n = str.length();
 6          int m = pattern.length();
 7          boolean[][] T = new boolean[n + 1][m + 1];
 8  
 9          T[0][0] = true; // Empty pattern matches empty string
10  
11          // Fill first row for patterns like "*", "**", etc.
12          for (int j = 1; j <= m; j++) {
13              if (pattern.charAt(j - 1) == '*') {
14                  T[0][j] = T[0][j - 1];
15              }
16          }
17  
18          // Fill the T table
19          for (int i = 1; i <= n; i++) {
20              for (int j = 1; j <= m; j++) {
21                  if (pattern.charAt(j - 1) == '?' || pattern.charAt(j - 1) == str.charAt(i - 1)) {
22                      T[i][j] = T[i - 1][j - 1]; // Match single character
23                  } else if (pattern.charAt(j - 1) == '*') {
24                      T[i][j] = T[i - 1][j] || T[i][j - 1]; // '*' matches empty or one/more chars
25                  }
26              }
27          }
28          
29          return T[n][m];
30      }
31  
32      public static void main(String[] args) {
33          
34          Scanner sc = new Scanner(System.in);
35  
36          System.out.print("Enter the String: ");
37          String word = sc.nextLine();
38  
39          System.out.print("Enter the pattern: ");
40          String pattern = sc.nextLine();
41  
42          if (isMatch(word, pattern)) {
43              System.out.println("Pattern matches the string.");
44          } else {
45              System.out.println("Pattern does not match the string.");
46          }
47      }
48  }