Implement wildcard pattern matching with support for ‘?’ and ‘*’.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false
Let’s see the answer!
public class Solution {
public boolean isMatch(String str, String pattern) {
int s = 0, p = 0, match = 0, starIdx = -1;
while (s < str.length()) {
// case that: str[s] == pattern[p] or pattern[p] == '?'
if (p < pattern.length() && (pattern.charAt(p) == '?' || str.charAt(s) == pattern.charAt(p))) {
s++;
p++;
}
// case that * found, only advance the pattern pointer.
else if (p < pattern.length() && pattern.charAt(p) == '*') {
starIdx = p;
match = s;
p++;
}
// case that pattern[p] != str[s] && pattern[p] != '?' && pattern[p] != '*', that
// means la
else if (starIdx != -1) {
p = starIdx + 1;
match++;
s = match;
}
// case that current pattern pointer is not *, and last pointer was not * either. So, don't match.
else return false;
}
// Let's check for remaining character in pattern
while (p < pattern.length() && pattern.charAt(p) == '*') {
p++;
}
return p == pattern.length();
}
}
Dynamic Programing
Can also solvle it with DP method!
1. Python Code
class Solution:
# @param s, an input string
# @param p, a pattern string
# @return a boolean
def isMatch(self, s, p):
m,n = len(s),len(p)
cnt =p.count('*')
if n - cnt > m:
return False
dp=[True] + [False]*n
for j in range(1,n+1):
dp[j]= dp[j-1] and p[j-1]=='*'
for i in range(1,m+1):
cur=[False]*(n+1)
for j in range(1,n+1):
if p[j-1]=='*':
cur[j]= cur[j-1] or dp[j]
elif p[j-1]==s[i-1] or p[j-1]=='?':
cur[j]=dp[j-1]
dp=cur
return dp[n]
- Java Code
public class Solution {
public boolean isMatch(String s, String p) {
int m = s.length(), n = p.length();
int count = 0;
for (int i = 0; i < n; i++) {
if (p.charAt(i) == '*') count++;
}
if (count==0 && m != n) return false;
else if (n - count > m) return false;
boolean[] match = new boolean[m+1];
match[0] = true;
for (int i = 0; i < m; i++) {
match[i+1] = false;
}
for (int i = 0; i < n; i++) {
if (p.charAt(i) == '*') {
for (int j = 0; j < m; j++) {
match[j+1] = match[j] || match[j+1];
}
} else {
for (int j = m-1; j >= 0; j--) {
match[j+1] = (p.charAt(i) == '?' || p.charAt(i) == s.charAt(j)) && match[j];
}
match[0] = false;
}
}
return match[m];
}
}