|
| 1 | +public class WildcardMatching { |
| 2 | + |
| 3 | + // Function to check if string s matches pattern p |
| 4 | + public boolean isMatch(String s, String p) { |
| 5 | + int n = s.length(); |
| 6 | + int m = p.length(); |
| 7 | + |
| 8 | + // DP table: dp[i][j] = does s[0..i-1] match p[0..j-1] ? |
| 9 | + boolean[][] dp = new boolean[n + 1][m + 1]; |
| 10 | + |
| 11 | + // Base case: empty string matches empty pattern |
| 12 | + dp[0][0] = true; |
| 13 | + |
| 14 | + // Fill for patterns that start with '*' |
| 15 | + // e.g., s = "" and p = "***" should be true |
| 16 | + for (int j = 1; j <= m; j++) { |
| 17 | + if (p.charAt(j - 1) == '*') { |
| 18 | + dp[0][j] = dp[0][j - 1]; // '*' can represent empty string |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + // Fill the DP table |
| 23 | + for (int i = 1; i <= n; i++) { |
| 24 | + for (int j = 1; j <= m; j++) { |
| 25 | + char sc = s.charAt(i - 1); // current char in string |
| 26 | + char pc = p.charAt(j - 1); // current char in pattern |
| 27 | + |
| 28 | + if (pc == sc || pc == '?') { |
| 29 | + // If chars match OR '?' wildcard, carry forward diagonal |
| 30 | + dp[i][j] = dp[i - 1][j - 1]; |
| 31 | + } else if (pc == '*') { |
| 32 | + // '*' can represent: |
| 33 | + // 1. empty sequence -> dp[i][j-1] |
| 34 | + // 2. one or more characters -> dp[i-1][j] |
| 35 | + dp[i][j] = dp[i][j - 1] || dp[i - 1][j]; |
| 36 | + } else { |
| 37 | + dp[i][j] = false; // mismatch |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + // Answer is whether entire s matches entire p |
| 43 | + return dp[n][m]; |
| 44 | + } |
| 45 | + |
| 46 | + // ---------------------------- |
| 47 | + // Example Usage |
| 48 | + // ---------------------------- |
| 49 | + public static void main(String[] args) { |
| 50 | + WildcardMatching solver = new WildcardMatching(); |
| 51 | + |
| 52 | + System.out.println(solver.isMatch("aa", "a")); // false |
| 53 | + System.out.println(solver.isMatch("aa", "*")); // true |
| 54 | + System.out.println(solver.isMatch("cb", "?a")); // false |
| 55 | + System.out.println(solver.isMatch("adceb", "*a*b")); // true |
| 56 | + System.out.println(solver.isMatch("acdcb", "a*c?b")); // false |
| 57 | + } |
| 58 | +} |
0 commit comments