-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy path44-wildcard-matching.java
More file actions
58 lines (48 loc) · 1.74 KB
/
44-wildcard-matching.java
File metadata and controls
58 lines (48 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
44. Wildcard Matching
Hard - 30.7%
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:
- '?' Matches any single character.
- '*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
Example 1:
Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input: s = "aa", p = "*"
Output: true
Explanation: '*' matches any sequence.
Example 3:
Input: s = "cb", p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.
*/
class Solution {
public boolean isMatch(String s, String p) {
int m = s.length(), n = p.length();
boolean[][] dp = new boolean[m + 1][n + 1];
// Base case: empty string matches empty pattern
dp[0][0] = true;
// Handle patterns like a* or *a* etc.
for (int j = 1; j <= n; j++) {
if (p.charAt(j - 1) == '*') {
dp[0][j] = dp[0][j - 1];
}
}
// Fill the DP table
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (p.charAt(j - 1) == '*') {
// '*' can match empty sequence or any character
dp[i][j] = dp[i - 1][j] || dp[i][j - 1];
} else if (p.charAt(j - 1) == '?' || s.charAt(i - 1) == p.charAt(j - 1)) {
// '?' matches any character, or exact character match
dp[i][j] = dp[i - 1][j - 1];
}
// else dp[i][j] remains false (no match)
}
}
return dp[m][n];
}
}