剑指offer JavaScript版 (52)

正则表达式匹配

题目描述

请实现一个函数用来匹配包括’.‘和’‘的正则表达式。模式中的字符’.‘表示任意一个字符,而’'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"abaca"匹配,但是与"aa.a"和"ab*a"均不匹配

  • 第二个字符为"*"
    • 第一个字符为"."或为等于s此时的字符
    • 第一个字符不为"."且第一个字符也不匹配s此时的字符
  • 第二个字符不为"*"
    • 第一个字符为"."或第一个字符匹配s此时的字符

function match(s, pattern)
{
    // write code here
    if(s==null||pattern==null)return false;
    return matchrecursive(s,0,pattern,0);
}
function matchrecursive(str,istr,pattern,ipattern){
    if(str.length==istr&&pattern.length==ipattern)
        return true;
    if(str.length!=istr&&pattern.length==ipattern){
        return false;
    }
    if(pattern[ipattern+1]=='*'){
        if(pattern[ipattern]=='.'&&istr!=str.length||pattern[ipattern]==str[istr]){
            return (
                matchrecursive(str,istr+1,pattern,ipattern+2)||
                matchrecursive(str,istr+1,pattern,ipattern)||
                matchrecursive(str,istr,pattern,ipattern+2)
            )
            
        }
        return matchrecursive(str,istr,pattern,ipattern+2)
    }
    if(pattern[ipattern]=='.'&&istr!=str.length||pattern[ipattern]==str[istr]){
        return matchrecursive(str,istr+1,pattern,ipattern+1)
    }
    return false;
}
发布了93 篇原创文章 · 获赞 3 · 访问量 2487

猜你喜欢

转载自blog.csdn.net/Damp_XUN/article/details/99328644