Java String Program · S56
Wildcard Pattern Matching in Java
? matches exactly one character and * matches any sequence, including none. The whole string must match the whole pattern.
Problem Statement
Given a string s and a pattern p, return true if the pattern matches the entire string. In the pattern, ? matches any single character and * matches any sequence of characters, including the empty sequence.
All other pattern characters must match exactly.
Input/Output Examples
s = "javabytechie", p = "java*e"OutputtrueExplanation: * matches "bytechi" and the final e matches e.s = "abce", p = "a?d*"OutputfalseExplanation: ? matches b, but d does not match c.s = "ab", p = "*b"OutputtrueExplanation: * matches a.Visual Explanation
| s \ p | ∅ | * | b |
|---|---|---|---|
| ∅ | T | T | F |
| a | F | T | F |
| b | F | T | T |
s = "ab" and p = "*b": T means the prefixes match. The star column is true wherever the star can absorb the characters so far (amber), and the final cell (purple) is true.A star cell is true if the star matches nothing (the cell to the left) or one more character (the cell above). Any other pattern character copies the diagonal cell when it matches the current string character.
Approaches
The DP table checks every pair of prefixes. The greedy approach scans once and backtracks only to the most recent star.
Approach 1: Dynamic Programming Table (Recommended)
Idea: dp[i][j] is true when the first i characters of s match the first j characters of p.
dp[0][0]is true;dp[0][j]is true while the pattern so far is all stars.- For
*,dp[i][j] = dp[i][j - 1] || dp[i - 1][j]. - For
?or an equal character,dp[i][j] = dp[i - 1][j - 1]. - Return
dp[n][m].
Time: O(n × m) · Space: O(n × m).
Approach 2: Greedy With Star Backtracking
Idea: match characters directly; when stuck, return to the last star and let it absorb one more character.
- On
?or an equal character, advance both pointers. - On
*, remember its position and the current string index. - On a mismatch after a star, let the star take one more character and retry.
- At the end, skip trailing stars and check that the pattern is used up.
Time: O(n × m) · Space: O(1). Usually close to linear in practice.
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Dynamic Programming Table (Recommended)
Every case is explicit, which makes the solution easy to verify and to adapt.
public class WildcardDp {
// dp[i][j] = do the first i chars of s match the first j chars of p?
static boolean isMatch(String s, String p) {
int n = s.length();
int m = p.length();
boolean[][] dp = new boolean[n + 1][m + 1];
dp[0][0] = true;
for (int j = 1; j <= m && p.charAt(j - 1) == '*'; j++) {
dp[0][j] = true; // leading stars can match nothing
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
char pc = p.charAt(j - 1);
if (pc == '*') {
dp[i][j] = dp[i][j - 1] || dp[i - 1][j]; // star matches nothing, or one more char
} else if (pc == '?' || pc == s.charAt(i - 1)) {
dp[i][j] = dp[i - 1][j - 1];
}
}
}
return dp[n][m];
}
public static void main(String[] args) {
String[][] cases = {{"javabytechie", "java*e"}, {"abce", "a?d*"}, {"ab", "*b"}};
for (String[] c : cases) {
System.out.println("s=\"" + c[0] + "\", p=\"" + c[1] + "\" -> " + isMatch(c[0], c[1]));
}
}
}
s="javabytechie", p="java*e" -> true s="abce", p="a?d*" -> false s="ab", p="*b" -> true
Time complexity: O(n × m) · Space complexity: O(n × m).
Approach 2: Greedy With Star Backtracking
Only the most recent star matters, because an earlier star can never need to match more than a later one already can.
public class WildcardGreedy {
// Match greedily; on a dead end, let the most recent '*' absorb one more character
static boolean isMatch(String s, String p) {
int i = 0;
int j = 0;
int star = -1;
int matchedByStar = 0;
while (i < s.length()) {
if (j < p.length() && (p.charAt(j) == '?' || p.charAt(j) == s.charAt(i))) {
i++;
j++;
} else if (j < p.length() && p.charAt(j) == '*') {
star = j++;
matchedByStar = i; // star matches nothing for now
} else if (star != -1) {
j = star + 1;
i = ++matchedByStar; // star takes one more character
} else {
return false;
}
}
while (j < p.length() && p.charAt(j) == '*') {
j++; // trailing stars match nothing
}
return j == p.length();
}
public static void main(String[] args) {
String[][] cases = {{"javabytechie", "java*e"}, {"abce", "a?d*"}, {"ab", "*b"}};
for (String[] c : cases) {
System.out.println("s=\"" + c[0] + "\", p=\"" + c[1] + "\" -> " + isMatch(c[0], c[1]));
}
}
}
s="javabytechie", p="java*e" -> true s="abce", p="a?d*" -> false s="ab", p="*b" -> true
Time complexity: O(n × m) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Dynamic Programming Table | O(n × m) | O(n × m) |
| Greedy With Star Backtracking | O(n × m) | O(1) |
Here n is the length of the string and m the length of the pattern. The table has (n + 1) × (m + 1) cells; the greedy scan uses constant memory and is fast on typical patterns.
Interview Tips and Recommended Approach
- Handle leading stars. They allow matches against the empty prefix, so the first row needs special initialisation.
- Collapse repeated stars.
**behaves like*, which can simplify the pattern first. - Do not confuse with regex. In regex,
*repeats the previous character; here it matches any sequence. - Explain the greedy shortcut. Backtracking to only the last star is the key insight.
Recommended Approach: Dynamic Programming Table
Why: it states each rule of the problem directly as a recurrence, which makes it hard to get wrong and easy to explain, before discussing the constant-space greedy version.