LeetCode 10. Regular Expression Matching

本文介绍了一种实现正则表达式匹配的算法,重点讨论了支持‘.’和‘*’两种特殊字符的情况。通过递归和动态规划两种方法解析不同情况下的匹配规则,并给出了具体的代码实现。

题目:

  • Implement regular expression matching with support for ‘.’ and ‘*’.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true

思路:

  • 对于isMatch("abab", ".*ab"),由于.*可以匹配空,也可以匹配ab,可能性较多,使用动态规划解决比较合适。
  • 子问题很清楚,就是找出子字符串是否匹配。
  • 状态转移如下(a代表某一字符,b代表某一非a字符,x代表a后面的字符串,~代表正则后面的字符串。)
\字符串格式正则格式下一状态字符串下一状态正则示例
情况一axa*~ 或.*~ax~isMatch(“ab”,”a*ab”)
xa*~ 或.*~isMatch(“aa”,”a*”)
情况二axb*~ax~isMatch(“aa”,”b*aa”)
情况三axa~或.~x~isMatch(“ab”,”.b”)
情况四axb~falsefalseisMatch(“aa”,”ba”)

代码:

public boolean isMatch(String s, String p) {
        //s或p为空时
        if("".equals(s)&&"".equals(p))return true;//两者都是空,匹配成功
        if("".equals(s)&&p.length()>=2&&"*".equals(p.substring(1,2)))return isMatch(s,p.substring(2));//字符串已经空了,正则要能与空匹配
        if("".equals(s)||"".equals(p))return false;//其他情况某一种为空,匹配失败。

        //s不为空时
        String item = s.substring(0,1);
        String rest = s.substring(1);
        //情况一
        if(p.startsWith(".*")||p.startsWith(item+"*")){
            return isMatch(s,p.substring(2))||isMatch(rest,p);
        }
        //情况二
        if(p.length()>=2&&"*".equals(p.substring(1,2))){
            return isMatch(s,p.substring(2));
        }
        //情况三
        if(p.startsWith(".")||p.startsWith(item)){
            return isMatch(rest,p.substring(1));
        }
        //情况四
        return false;
    }

改进:

  • 使用递归替换迭代。(原来由后向前,现在由前向后)
  • 使用二维动态规划,二维数组保存中间状态,防止重复计算。
  • 对于正则字符串,每次也只读取一个字符。之前的做法需要把*和前面的字符一起考虑。

例子:isMatch(“b”,”a*b”),有dp矩阵如下

dp0123
0truefalsetruefalse
1falsefalsefalsetrue

特征:

1. dp[0][0]=true;
2. dp[n][0]=false;n>0
3. dp[0][2n-1]=false;n>0
4. dp[0][2n]=p[2n]==*?dp[0][2n-2]:false;n>0
5. dp[i][j]=function(){
    if((p[j]==s[i]||p[j]=='.'))return dp[i-1][j-1];
    if(p[j]=='*'){
        if((p[j-1]!=s[i])&&p[j-1]!='.') {
        //*前的字符和当前待匹配字符不一致,此*代表出现0次。
                    return dp[i][j-2];
                } else {
                //*代表出现1次或出现>1次或出现0次
                        return (dp[i][j-1] || dp[i-1][j] || dp[i][j-2]);
                    }
    }
}

代码:

public boolean isMatch(String s, String p) {
        boolean[][] dp = new boolean[s.length()+1][p.length()+1];
        dp[0][0]=true;
        for (int i = 1; i < p.length(); i+=2) {
            if (p.charAt(i) == '*' && dp[0][i-1]) {
                dp[0][i+1] = true;
            }
        }
        for (int i = 0 ; i < s.length(); i++) {
            for (int j = 0; j < p.length(); j++) {
                if(p.charAt(j) == '.'||p.charAt(j) == s.charAt(i)){
                    dp[i+1][j+1]=dp[i][j];
                }
                if (p.charAt(j) == '*') {
                    if (p.charAt(j-1) != s.charAt(i) && p.charAt(j-1) != '.') {
                        dp[i+1][j+1] = dp[i+1][j-1];
                    } else {
                        dp[i+1][j+1] = (dp[i+1][j] || dp[i][j+1] || dp[i+1][j-1]);
                    }
                }
            }
        }
        return dp[s.length()][p.length()];
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值