题目描述
请实现一个函数用来匹配包括’.‘和’‘的正则表达式。模式中的字符’.‘表示任意一个字符,而’'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"abaca"匹配,但是与"aa.a"和"ab*a"均不匹配
public class Solution {
public boolean match(char[] str, char[] pattern)
{
return matchCore(str,0,pattern,0);
}
private boolean matchCore(char[] str,int sIndex ,char[] pattern,int pIndex){
if(sIndex==str.length&&pIndex==pattern.length)
return true;
if(sIndex!=str.length&&pIndex==pattern.length)
return false;
if((pIndex==pattern.length-1||pattern[pIndex+1]!='*')){
//当模式中的下一个元素不是'*'或者没有下个元素时,只需要比较当前元素
if(sIndex>=str.length)
return false;
if(pattern[pIndex]=='.'||str[sIndex]==pattern[pIndex])
return matchCore(str,sIndex+1,pattern,pIndex+1);
else
return false;
}
else //if(pattern[pIndex+1]=='*') //当模式的下一个元素是'*'时
{
if(sIndex==str.length)//当字符串到达结尾时,模式需要*置零的方式到达结尾
return matchCore(str,sIndex,pattern,pIndex+2);
if(sIndex<str.length&&(str[sIndex]==pattern[pIndex]||pattern[pIndex]=='.')){//当匹配时,此时有三种情况
return matchCore(str,sIndex+1,pattern,pIndex)//*代表出现大于1次时
||matchCore(str,sIndex+1,pattern,pIndex+2)//*代表出现1次时
||matchCore(str,sIndex,pattern,pIndex+2);//*代表出现0次时
}
else//当模式与字符串不匹配,此时*需要使得前面的字符出现零次。
return matchCore(str,sIndex,pattern,pIndex+2);//*代表出现0次时
}
}
}