44. Wildcard Matching
题目
Given an input string (s) and a pattern §, implement wildcard pattern matching with support for ‘?’ and ‘*’.
- ‘?’ Matches any single character.
- ‘*’ Matches any sequence ofcharacters (including the empty sequence).
The matching should cover the entire input string (not partial).
Note:
- s could be empty and contains only lowercase letters a-z.
- p could be empty and contains only lowercase letters a-z, and characters like ? or *.
给定一个字符串 (s) 和一个字符模式 § ,实现一个支持 ‘?’ 和 ‘*’ 的通配符匹配。
- ‘?’ 可以匹配任何单个字符。
- ‘*’ 可以匹配任意字符串(包括空字符串)。
两个字符串完全匹配才算匹配成功。
说明:
- s 可能为空,且只包含从 a-z 的小写字母。
- p 可能为空,且只包含从 a-z 的小写字母,以及字符 ? 和 *。
Example
Input:
s = “aa”
p = “a”
Output: false
Explanation: “a” does not match the entire string “aa”.
Input:
s = “aa”
p = ""
Output: true
Explanation: '’ matches any sequence.
Input:
s = “cb”
p = “?a”
Output: false
Explanation: ‘?’ matches ‘c’, but the second letter is ‘a’, which does not match ‘b’.
Input:
s = “adceb”
p = “ab”
Output: true
Explanation: The first ‘’ matches the empty sequence, while the second '’ matches the substring “dce”.
Input:
s = “acdcb”
p = “a*c?b”
Output: false
解法
动态规划, dp[i][j]表示s的前i个字符和p的前j个字符是否匹配得上
代码
public boolean isMatch(String s, String p) {
boolean[][] dp = new boolean[s.length()+1][p.length()+1];
dp[0][0] = true;
for(int i = 0; i < p.length(); i++) {
if(p.charAt(i) != '*')
break;
dp[0][i+1] = dp[0][i];
}
for(int i = 1; i <= s.length(); i++) {
for(int j = 1; j <= p.length(); j++) {
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-1] || dp[i-1][j] || dp[i][j-1];
}
}
return dp[s.length()][p.length()];
}
执行用时 : 56 ms, 在Wildcard Matching的Java提交中击败了79.93% 的用户
内存消耗 : 40.1 MB, 在Wildcard Matching的Java提交中击败了22.62% 的用户