-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy path44-wildcard-matching.cpp
More file actions
63 lines (52 loc) · 1.77 KB
/
44-wildcard-matching.cpp
File metadata and controls
63 lines (52 loc) · 1.77 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
59
60
61
62
63
/*
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'.
*/
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
bool isMatch(string s, string p) {
int m = s.length(), n = p.length();
vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));
// 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[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[j - 1] == '*') {
// '*' can match empty sequence or any character
dp[i][j] = dp[i - 1][j] || dp[i][j - 1];
} else if (p[j - 1] == '?' || s[i - 1] == p[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];
}
};