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
思路和10. Regular Expression Matching 相同:http://www.jianshu.com/p/8eac6ad7d856
reference: https://www.youtube.com/watch?v=9OnS06RYQiw
Solution:DP
思路:和10. Regular Expression Matching 相同,除了'*'代表意义的不同。这样dp上实现不同的是: 初始化, ‘*’时的更新
Time Complexity: O(mn) Space Complexity: O(mn)
Solution Code:
class Solution {
public boolean isMatch(String s, String p) {
if (s == null || p == null) {
return false;
}
boolean[][] dp = new boolean[p.length() + 1][s.length() + 1];
dp[0][0] = true;
// dp init
for (int i = 1; i <= p.length(); i++) {
if (p.charAt(i - 1) == '*') {
dp[i][0] = dp[i - 1][0];
}
}
// calc dp
for (int i = 1 ; i <= p.length(); i++) {
for (int j = 1; j <= s.length(); j++) {
if (p.charAt(i - 1) == s.charAt(j - 1) || p.charAt(i - 1) == '?') {
dp[i][j] = dp[i - 1][j - 1];
}
else if(p.charAt(i - 1) == '*') {
dp[i][j] = dp[i][j - 1] || dp[i - 1][j];
}
}
}
return dp[p.length()][s.length()];
}
}