1. Understand the Goal: The user wants a program that implements wildcard pattern matching. This typically means matching a string (let's call it s or text) against a pattern (p or pattern) containing wildcards like ? (matches any single character) and * (matches any sequence of characters, including an empty sequence).
-
Identify the Constraints & Requirements:
- Input: Two strings: a text string and a pattern string.
- Output: Boolean (True/False) indicating if the pattern matches the text.
- Wildcards:
? matches exactly one character.
* matches zero or more characters.
- Edge Cases: Empty strings, strings with multiple
*, strings starting/ending with *.
- Language: Python is usually the safest default for algorithmic examples unless specified otherwise, but I should probably provide a conceptual explanation and maybe a C++ or Java version if requested. I'll stick to Python for clarity but explain the logic so it's translatable.
-
Choose the Algorithm:
-
Select the Best Approach for the User:
- The DP approach is often easier to understand conceptually for "pattern matching" problems.
- The Greedy approach is the "optimal" solution.
- I will provide the Greedy approach as the primary solution because it's O(1) space and generally preferred, but I will also briefly mention the DP approach or structure the code so it's clear. Actually, usually, people asking this want the DP solution because it's the textbook "Wildcard Matching" problem (LeetCode 44). The Greedy one is tricky to get right.
- Decision: I will provide the Greedy approach as the primary code because it's cleaner (no extra matrix), but I will write the code very clearly with comments. I'll also offer the DP logic as an alternative explanation.
Let's refine the Greedy logic (Backtracking):
i (text index), j (pattern index)
last_star_idx (index in pattern where * was found), last_match_idx (index in text matched to that star)
- Loop while
i < len(text):
- If chars match or
?: advance i, j.
- If pattern is
*: last_star_idx = j, last_match_idx = i, j++.
- Else if mismatch:
- If
last_star_idx is set: we need to use the * to consume more text. j = last_star_idx + 1, last_match_idx += 1, i = last_match_idx.
- Else: return False.
- After text loop, check remaining chars in pattern. They must be all
*.
-
Drafting the Code (Python):
def is_match(text, pattern):
i, j = 0, 0
star_idx, match_idx = -1, 0
while i < len(text):
if j < len(pattern) and (pattern[j] == text[i] or pattern[j] == '?'):
i += 1
j += 1
elif j < len(pattern) and pattern[j] == '*':
star_idx = j
match_idx = i
j += 1
elif star_idx != -1:
# Backtrack: use * to consume current text char
j = star_idx + 1
match_idx += 1
i = match_idx
else:
return False
# Check remaining pattern characters
while j < len(pattern) and pattern[j] == '*':
j += 1
return j == len(pattern)
-
Drafting the Code (C++):
Since this is a common algorithmic problem, providing C++ is good practice.
-
Refining the Output Structure:
- Introduction: Define what
? and * do.
- Approach: Explain the Two-Pointer Greedy strategy (it's the most efficient).
- Code Implementation: Provide Python (high readability) and C++ (performance/standard).
- Example Usage: Show test cases.
-
Reviewing the Greedy Logic (Self-Correction):
Does the greedy logic cover text = "aa", pattern = "*"?
- i=0, j=0.
p[0] is *. star_idx=0, match_idx=0, j=1.
- Loop continues.
i=0, j=1. j is out of bounds? No, j < len check.
- Wait, inside loop:
if j < len (False)
elif j < len (False)
elif star_idx != -1 (True):
j becomes 1. match_idx becomes 1. i becomes 1.
- Loop:
i=1. j=1 (out of bounds).
star_idx != -1 triggers again.
match_idx becomes 2. i becomes 2.
- Loop ends (i=2).
- Remaining pattern check:
j=1, len=1. Done.
- Returns True. Correct.
Does it cover text="cb", pattern="?a"?
c vs ?: match. i=1, j=1.
b vs a: mismatch. No star. Returns False. Correct.
Does it cover text="adceb", pattern="*a*b"?
*: star=0, match=0, j=1.
a vs a: match. i=1, j=2.
d vs *: match. star=2, match=1, .
This solution uses the Greedy Approach with Backtracking. It is preferred over Dynamic Programming for this specific problem because it reduces the space complexity from O(M×N) to O(1), making it much faster for longer strings.
The Algorithm
We use two pointers, i for the string and j for the pattern.
- If characters match, or pattern has
?, advance both pointers.
- If pattern has
*, we mark this position (star_idx) and the current string position (match_idx), then move the pattern pointer forward (assuming * matches an empty sequence).
- If a mismatch occurs:
- If we have encountered a
* previously, we backtrack: we increment the match_idx (making the * consume one more character from the string) and reset the string pointer i to this new position.
- If we haven't seen a
*, the match fails.
- After processing the string, any remaining characters in the pattern must be
*.
Python Implementation
def is_match(text: str, pattern: str) -> bool:
"""
Returns True if the 'text' matches the 'pattern'.
'?' Matches any single character.
'*' Matches any sequence of characters (including empty sequence).
"""
# Pointers for the text and pattern
i = 0
j = 0
# Pointers to track the last position of '*' in pattern
# and the position in text when that '*' was encountered
star_idx = -1
match_idx = 0
len_t = len(text)
len_p = len(pattern)
while i < len_t:
# 1. If characters match, or pattern is '?', advance both
if j < len_p and (pattern[j] == text[i] or pattern[j] == '?'):
i += 1
j += 1
# 2. If pattern is '*', record the position and advance pattern pointer
elif j < len_p and pattern[j] == '*':
star_idx = j
match_idx = i
j += 1
# 3. If mismatch occurs, but we have a recorded '*' from the past,
# backtrack: make the '*' consume one more character of text.
elif star_idx != -1:
j = star_idx + 1
match_idx += 1
i = match_idx
# 4. If mismatch and no '*' to fallback on, return False
else:
return False
# After finishing the text, check if remaining pattern characters are all '*'
while j < len_p and pattern[j] == '*':
j += 1
# If we have consumed the entire pattern, it's a match
return j == len_p
# --- Test Cases ---
test_cases = [
("file.txt", "file.txt", True),
("file.txt", "*.txt", True),
("file.txt", "f*.txt", True),
("image.jpg", "*.png", False),
("data", "d?t?", True),
("data", "d?r?", False),
("abc", "a*", True),
("abc", "*", True),
("", "*", True),
("", "?", False),
("abcde", "a*de", True),
("abcde", "a*d?", True),
("mississippi", "m??*ss*?i*pi", False)
]
print(f"{'Text':<15} | {'Pattern':<15} | {'Result':<10} | {'Expected':<10}")
print("-" * 60)
for text, pat, expected in test_cases:
result = is_match(text, pat)
status = "✅" if result == expected else "❌"
print(f"{text:<15} | {pat:<15} | {str(result):<10} | {str(expected):<10} {status}")
C++ Implementation
Here is the same logic implemented in C++.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool isMatch(const string &text, const string &pattern) {
int i = 0; // pointer for text
int j = 0; // pointer for pattern
int star_idx = -1; // index of '*' in pattern
int match_idx = 0; // index in text matching against '*'
int len_t = text.length();
int len_p = pattern.length();
while (i < len_t) {
// 1. Match or '?'
if (j < len_p && (pattern[j] == text[i] || pattern[j] == '?')) {
i++;
j++;
}
// 2. '*' found
else if (j < len_p && pattern[j] == '*') {
star_idx = j;
match_idx = i;
j++;
}
// 3. Mismatch, but we have a previous '*' to use
else if (star_idx != -1) {
j = star_idx + 1; // reset pattern pointer to after star
match_idx++; // make star consume one more char
i = match_idx; // reset text pointer
}
// 4. Mismatch and no star
else {
return false;
}
}
// Check for remaining characters in pattern
while (j < len_p && pattern[j] == '*') {
j++;
}
return j == len_p;
}
int main() {
cout << boolalpha; // print true/false instead of 1/0
cout << "Match 'file.txt' with '*.txt': " << isMatch("file.txt", "*.txt") << endl;
cout << "Match 'cat' with 'c?t': " << isMatch("cat", "c?t") << endl;
cout << "Match 'abc' with 'a*': " << isMatch("abc", "a*") << endl;
cout << "Match 'abc' with '?': " << isMatch("abc", "?") << endl;
return 0;
}
Complexity Analysis
- Time Complexity: O(M×N) in the worst case.
- M is the length of the text, N is the length of the pattern.
- While the logic looks linear, in cases with many
* characters causing backtracking (e.g., Text: "aaaaaaaa...", Pattern: "*a*b*c"), the inner loop might execute multiple times for a single character.
- However, on average, it performs much closer to than the standard Dynamic Programming approach.