- 问题介绍
- 问题描述:
- 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).
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 *.
- 示例:
- Input:
- Output
- Explanation:
- The first ‘*’ matches the empty sequence, while the second ‘*’ matches the substring "dce”.
- 解决方案
- 解法一:
- 思路:
- 对于给定的两个字符串s和p,每次比较字符串的第一个元素,存在有限的情况:
- 情况1:s[0]p[0]或者p[0]‘?’,在这中情况下属于s和p串对于头元素匹配成功,继续匹配两个字符串后面的元素;
- 情况2:s[0]!=p[0]且p[0]!=‘*’,在这种情况下属于s和p串匹配失败,直接返回false;
- 情况3:s[0]!=p[0]且p[0]==‘*’,对于*这个字符来说,他可以匹配s串中的当前位置到末尾的所有元素或者不匹配任何元素即表示空,所以对于这种情况我们可以分为两部分处理。一是假设*没有匹配任何字符,则将*后面的字符串生成新的p再与s比较;二是假设*匹配了字符,则可以将s当前字符后面的字符串生成新的s再与p比较,此时p不变;
- 分析完比较的情况后,可以发现使用递归可以很好的模拟这一过程,大问题可以分解成相同的子问题,且存在一个问题结束的点,那就是:
- 当p串为空后,如果s串也为空则返回true,否则返回false;
- 当s串为空后,如果p串不为空,且头元素不为*,则返回false;
- 存在的问题:
- 当输入字符串s很长,匹配串p很复杂的时候即含有较多的*号,该算法的时间将呈指数级增高,不符合时间复杂度要求;
- 代码:
class Solution {
public:
bool isMatch(string s, string p) {
if(p.length()==0)
{
return s.length()==0;
}
else if(s.length()==0)
{
if(p.length()>0&&p[0]=='*')
return isMatch(s,p.substr(1));
else
return false;
}
else
{
if(s[0]==p[0]||p[0]=='?')
{
return isMatch(s.substr(1),p.substr(1));
}
else
{
if(p[0]=='*')
{
if(isMatch(s.substr(1),p))
return true;
else
return isMatch(s,p.substr(1));
}
else
return false;
}
}
}
};
- 解法二:
- 思路:
- 解法一时间复杂度过高的主要原因是其存在过多的重复计算,我们可以使用一个二位数组resp[s.length()][p.length()]来记录已经比较过的位置,即s在i位置,p在j位置的时候,两个串从开始位置到i和j能否匹配用resp[i][j]表示;
- 那么就存在resp的计算公式:
- 当s[i] == p[j]或者p[j]=‘?’的时候,resp[i][j]==resp[i-1][j-1];
- 当p[j]=‘*’的时候,resp[i][j]==resp[i-1][j] || resp[i][j-1];
- 当整个resp数组计算完成后,resp[s.length()][p.length()]的值,就是我们所需要的结果了;此时的时间复杂度仅有O(m*n);
- 代码:
class Solution {
public:
bool isMatch(string s, string p) {
int m=s.length();
int n=p.length();
bool resp[s.length()+1][p.length()+1];
for(int i=0;i<s.length()+1;i++)
{
for(int j=0;j<p.length()+1;j++)
{
resp[i][j]=false;
}
}
resp[0][0]=true;
for(int i=1;i<=n;i++)
{
resp[0][i]=resp[0][i-1]&&p[i-1]=='*';
}
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
if(p[j-1]==s[i-1]||p[j-1]=='?')
{
resp[i][j]=resp[i-1][j-1];
}
else if(p[j-1]=='*')
{
resp[i][j]=resp[i-1][j]||resp[i][j-1];
}
else
resp[i][j]=false;
}
}
return resp[m][n];
}
};