44. Wildcard Matching
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
Solution:
- dp[i][j] represent string s from [0,i] matches with string p from [0,j]
- initialization:
- dp[0][0] = true
- dp[i][0] = false
- dp[0][j] only = true when all the character starting from position 0 = '*'
- update
- if s.char = p.char || p.char == '?'
- dp[i][j] = dp[i-1][j-1]
- if p.char = '*'
- dp[i][j] = dp[i-1][j] || dp[i][j-1] ----> *represent n or 0 elements
- otherwise
- false
- if s.char = p.char || p.char == '?'
public boolean isMatch(String s, String p) {
boolean[][] dp = boolean[s.length()+1][p.length()+1];
dp[0][0] = true;
for(int i = 1; i <= p.length(); i++){
if(p.charAt(i-1) =='*'){
dp[0][i] = dp[0][j-1];
}
}
for(int i = 1; i <= s.length(); i++){
for(int j = 1; j <= p.length(); p++){
if(s.charAt(i-1) == p.charAt(j-1) || p.charAt(j-1) == '.'){
dp[i][j] = dp[i-1][j-1];
}else if(p.charAt(j-1) == '*'){
dp[i][j] = (dp[i-1][j] || dp[i][j-1]);
}
}
}
return dp[s.length()][p.length()];
}