Given a string (s) and a character mode (p), to support the realization of a '?' And '*' wildcard match.
'?' Matches any single character.
'*' Matches any string (including the empty string).
Two strings match exact match is considered successful.
Description:
s may be empty, and only lowercase letters az from the.
p may be empty and contain only lowercase letters from az, and characters? and *.
Example 1:
Input:
S = "AA"
P = "A"
Output: false
interpretation: "a" can not match the entire string "aa".
Example 2:
Input:
S = "AA"
P = "*"
Output: true
interpretation: '*' matches any string.
Example 3:
Input:
S = "CB"
P = "A?"
Output: false
interpretation: '?' Match 'c', but the second 'a' not matched 'b'.
Example 4:
Input:
S = "adceb"
P = "A * B *"
Output: true
explained: the first '*' can match the empty string, the second '*' matches the string "dce".
Example 5:
Input:
S = "acdcb"
P = "? A B C *"
Input: false
Ideas: and leetcode10 almost, but this * can represent any character, and a character before and it does not matter, dp formula good push a lot.
class Solution {
public boolean isMatch(String s,String p){
if (s == null || p == null)return false;
int sLen=s.length();
int pLen=p.length();
boolean[][] dp = new boolean[sLen + 1][pLen + 1];
dp[0][0] = true;//dp[i][j] 表示 s 的前 i 个是否能被 p 的前 j 个匹配
for (int j=1;j<=pLen;j++)dp[0][j]=p.charAt(j-1)=='*' && dp[0][j-1];
for (int i = 0; i < sLen; i++) {
for (int j = 0; j < pLen; j++) {
//单个字符可以匹配
if (p.charAt(j) == '?' || p.charAt(j) == s.charAt(i)) dp[i + 1][j + 1] = dp[i][j];
//多个字符
if (p.charAt(j) == '*') {
dp[i+1][j+1]=dp[i+1][j] || //*代表0个
dp[i][j+1]; //代表多个
}
}
}
return dp[sLen][pLen];
}
}