Wild Card Matching
题目
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 letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like ? or *.
Example 1:
1 | |
Example 2:
1 | |
Example 3:
1 | |
Example 4:
1 | |
Example 5:
1 | |
解题报告
理解题意
2个 字符串,长度可能不相等,一个输入字符串,一个是模式字符串?表示匹配任意单一字符串*表示匹配任意字符串序列(包含空字符串)- 对
完整的输入字符串匹配 - 输入的还有:
小写字母或者空字符
理解例子
aa与a,单独的a不能完整匹配aaaa与*,*可以匹配任意字符串cb与?a, 从后往前看a和b并不匹配abceb与*a*b如下图
acdcb与a*c?b如下图
思路
- 碰到字符且模式串也是字符,直接比较就行
- 碰到
?跳过往前匹配即可,?就表示匹配, - 碰到
*会比较麻烦,因为会匹配>= 0个字符 - 但一般这种类型的题目可以使用动态规划来解决
代码
Dynamic Programming
- 假定
dp_[i][j]表示 匹配串(长为 i)s[0..i-1]与模式串(长为 j)p[0..j-1]是否匹配, - 首先什么都没有肯定是相互匹配的,那么
dp_[0][0] = true dp_[1...i-1][0] = false表示什么都没有和字符串不匹配dp_[0][j] = dp_[0][j-1]如果p[j-1] == *
1 | |
递归
时间复杂度
O(m*n)
空间复杂度
O(m*n)
Wild Card Matching