Given an input string (s
) and a pattern (p
), 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).
Note:
s
could be empty and contains only lowercase lettersa-z
.p
could be empty and contains only lowercase lettersa-z
, and characters like?
or*
.
Example 1:
Input: s = "aa" p = "a" Output: false Explanation: "a" does not match the entire string "aa".
Example 2:
Input: s = "aa" p = "*" Output: true Explanation: '*' matches any sequence.
Example 3:
Input: s = "cb" p = "?a" Output: false Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.
Example 4:
Input: s = "adceb" p = "*a*b" Output: true Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".
Example 5:
Input: s = "acdcb" p = "a*c?b" Output: false
class Solution { public boolean isMatch(String s, String p) { char[] sc = s.toCharArray(); char[] pc = p.toCharArray(); int m = sc.length, n = pc.length; boolean[][] dp = new boolean[m+1][n+1]; dp[0][0] = true; for(int i = 1; i < n + 1; i++){ if(pc[i-1] == '*') dp[0][i] = dp[0][i - 1]; } for(int i = 1; i < m + 1; i++){ for(int j = 1; j < n + 1; j++){ if(sc[i - 1] == pc[j - 1] || pc[j - 1] == '?'){ dp[i][j] = dp[i - 1][j - 1]; } else if(pc[j - 1] == '*'){ dp[i][j] = dp[i - 1][j] || dp[i][j - 1]; } } } return dp[m][n]; } }
行:string,列:pattern
第一行表示pattern和空字符匹配,除第一个外都为false。
第一列表示string和空pattern匹配,除pattern也为空为true外都为false。
row代表和pattern匹配的结果,col代表和string匹配的结果
如果pattern是*,在dp[i-1][j]是上一个pattern和当前string匹配结果,即将*看作empty string
dp[i][j-1]是将*与上一个string的匹配结果。