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
字符串匹配的问题应该最先想到dp,
主要还是说一下动态规划的方法。跟Regular Expression Matching一样,还是维护一个假设我们维护一个布尔数组res[i],代表s的前i个字符和p的前j个字符是否匹配(这里因为每次i的结果只依赖于j-1的结果,所以不需要二维数组,只需要一个一维数组来保存上一行结果即可),递推公式分两种情况:
(1)p[j]不是'*'。情况比较简单,只要判断如果当前s的i和p的j上的字符一样(如果有p在j上的字符是'?',也是相同),并且res[i]==true,则更新res[i+1]为true,否则res[i+1]=false;
(2)p[j]是'*'。因为'*'可以匹配任意字符串,所以在前面的res[i]只要有true,那么剩下的 res[i+1], res[i+2],...,res[s.length()]就都是true了。
算法的时间复杂度因为是两层循环,所以是O(m*n), 而空间复杂度只用一个一维数组,所以是O(n),假设s的长度是n,p的长度是m。代码如下:
public class Solution { public boolean isMatch(String s, String p) { int m = s.length(), n = p.length(); char[] ws = s.toCharArray(); char[] wp = p.toCharArray(); boolean[][] dp = new boolean[m+1][n+1]; dp[0][0] = true; for (int j = 1; j <= n; j++) dp[0][j] = dp[0][j-1] && wp[j-1] == '*'; for (int i = 1; i <= m; i++) dp[i][0] = false; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (wp[j-1] == '?' || ws[i-1] == wp[j-1]) dp[i][j] = dp[i-1][j-1]; else if (wp[j-1] == '*') dp[i][j] = dp[i-1][j] || dp[i][j-1]; } } return dp[m][n]; } }