LeetCode每日一练【10】

LeetCode每日一练 -- Regular Expression Matching

Funny

/*
 * @Author: fox
 * @Date: 2022-04-26 07:16:38
 * @LastEditors: fox
 * @LastEditTime: 2022-04-26 15:00:56
 * @Description: https://leetcode.com/problems/regular-expression-matching/
 */

/**
 * @param {string} s 目标字符串 
 * @param {string} p 正则表达式
 * @return {boolean}
 */
// em... I don't think that's what they want. But it's funny!
 const isMatch = (s, p) => {
    const re = RegExp(`^${p}$`, 'g')
    return re.test(s)
};

循环递归判断

/*
 * @Author: fox
 * @Date: 2022-04-26 07:16:38
 * @LastEditors: fox
 * @LastEditTime: 2022-04-26 18:14:20
 * @Description: https://leetcode.com/problems/regular-expression-matching/
 */

/**
 * @description: 递归循环判断
 * @param {string} s 目标字符串 
 * @param {string} p 正则表达式
 * @return {boolean}
 */
 const isMatch = (s, p) => {
    // 1. 如果正则表达式剩余字符串为空,判断返回结果
    if (!p || !p.length) return !Boolean(s.length);

    // 2. 匹配首字符 匹配成功,或者使用了通配符
    const matching = s.length && (p[0] === s[0] || p.startsWith('.'));

    // 3. 正则重复匹配
    if (p.length > 1 && p[1] === '*') {
        // 3.1.1  如果第二个是*字符 判断是否满足下列条件
        // 3.1.1.1 条件1 如果正则表达式字符串首字符匹配失败,*字符也就不需要再匹配,继续匹配正则表达式字符串剩下的部分
        const condition1 = isMatch(s, p.substring(2));
        // 3.1.1.2 条件2 首字符匹配成功,继续匹配正则表达式字符串的*字符
        const condition2 = matching && isMatch(s.substring(1), p);

        return condition1 || condition2
    } else {
        // 3.1.2 如果第二个不是*字符 递归判断下一个字符是否匹配
        return matching && isMatch(s.substring(1), p.substring(1));
    }
};
posted @ 2022-04-27 16:16  白い故雪  阅读(10)  评论(0编辑  收藏  举报