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(s,p). 这个函数的第一个参数是要匹配的字符串s,第二个参数是正则表达式。
规则如下:

'.' 可以用来匹配人以单个字符
‘*’ 可以用来匹配0个或者多个上一个字符。

除了使用效率较低的搜索算法,我们发现对于任意一个字符串,前n个字符的匹配 和后面的字符没有关系。所以我们可以用动态规划解这道题。 用match[i][j] 表示 字符串前i个字符 能否匹配 正则表达式前j个字符。
分情况讨论:

match[i][j]=match[i-j][j-1]          p[j]==s[i]  
match[i][j]=match[i-j][j-1]          p[j]!=s[i] && p[j]=='.'
match[i][j] = (match[i][j-1] || match[i-1][j] || match[i][j-2])       p[j]!=s[i] && p[j]=='*' && ( p[j-1]==s[i] || p[j-1]=='.')
match[i][j] = match[i][j-2]          p[j]!=s[i] && p[j]=='*' && ( p[j-1]!=s[i] && p[j-1]!='.')

前1、2、4情况都很好理解,下面举例说明第3种情况。
s: XXXXXXa
p: XXXXa*

s字符串的a 的位置是i, p字符串*的位置是j。
当* 代表一个a 的时候 :match[i][j-1]
当* 代表多个a的时候 :match[i-1][j]
当* 代表空字符串的时候 :match[i][j-2]

/**
 * @param {string} s
 * @param {string} p
 * @return {boolean}
 */
var isMatch = function(s,p) {
   let match=new Array(s.length+1);

    for (let i=0;i<=s.length;i++){
        let temp=new Array(p.length+1);
        temp.fill(false);
        match[i]=temp;
    }
     match[0][0] = true;

    for (let i = 0; i < p.length; i++) {
            match[0][i+1] = (p[i] == '*' && match[0][i-1]);
    }

    for (let i = 0 ; i < s.length; i++) {
        for (let j = 0; j < p.length; j++) {
            if (p[j] == '.') {
                match[i+1][j+1] = match[i][j];
            }
            if (p[j] == s[i]) {
                match[i+1][j+1] = match[i][j];
            }
            if (p[j] == '*') {
                if (p[j-1] != s[i] && p[j-1] != '.') {
                    match[i+1][j+1] = match[i+1][j-1];
                } else {
                    match[i+1][j+1] = (match[i+1][j] || match[i][j+1] || match[i+1][j-1]);
                }
            }
        }
    }
    return match[s.length][p.length];
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转自: JS正则表达式一条龙讲解,从原理和语法到JS正则、ES6正则扩展,最后再到正则实践思路 温馨提示:文章很长...
    前端渣渣阅读 1,841评论 1 32
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,771评论 0 33
  • 第5章 引用类型(返回首页) 本章内容 使用对象 创建并操作数组 理解基本的JavaScript类型 使用基本类型...
    大学一百阅读 3,270评论 0 4
  • 3月28日快递收到驾照,到今天两个月时间。 开公司的车加陪驾练车12小时,累积行驶里程3000多公里,没走过高速,...
    易简之旅阅读 155评论 0 0
  • 或许有莫多的遗憾, 或许被造作以及不堪回首的往事。 或许…… 但如今,知道了,是快乐。 糊涂了,也是快乐。 终究清...
    潇湘伊忆阅读 192评论 3 1