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
/*********************************************************/
又是一道我用naive方法做了很久,搞了半天,最后超时限。回过头来用动态规划做,一下就做完了的题目……
- 这道题动态规划的重点在于:用List[i][j]表示字符串s从0到i与字符串p从0到j进行匹配时的结果。当字符串p中j的位置是正确的字母或是?时,都非常简单,直接赋值List[i-1][j-1]即可。但如果p中j位置上是*,那么就变得复杂了。一种思路认为,当j位置上为*时
List[i][j] = List[i][j-1] || List[0][j-1] || List[1][j-1] || ........ || List[i-1][j-1]
因为当j位是*时,它可能不匹配,也可能匹配一个字符,也可能匹配n(0<=n<=i)个字符。
另一种思路则更简单——当j位置上为*时
List[i][j] = List[i][j-1] || List[i-1][j]
因为当*只要匹配一个以上的字符时,List[i][j] 的结果与 List[i-1][j] 一定是一样的。
有了思路代码就非常简单了,放上我自己的代码,语言是java
class Solution {
public boolean isMatch(String s, String p) {
int ls = s.length();
int lp = p.length();
boolean List[][] = new boolean[ls+1][lp+1];
for(int k = 1;k<=ls;k++)
List[k][0] = false;
List[0][0] = true;
for(int k = 0;k<lp && p.charAt(k) == '*' ;k++)
{
List[0][k+1] = true;
}
for(int j = 0; j<lp;j++)
{
for(int i = 0;i<ls;i++)
{
if(p.charAt(j)>='a' && p.charAt(j)<='z')
{
if(p.charAt(j) == s.charAt(i))
List[i+1][j+1] = List[i][j];
else List[i+1][j+1] = false;
}
else if(p.charAt(j)=='?')
{
List[i+1][j+1] = List[i][j];
}
else
{
List[i+1][j+1] = List[i][j+1] || List[i+1][j];
}
}
}
return List[ls][lp];
}
}