LeetCode (力扣) 10. Regular Expression Matching ( C ) - Hard - 递归法

本文探讨了如何使用递归实现字符串'.'和'*'的正则表达式匹配,通过实例解析规则并提供高效的C++代码。解题方法涉及处理'*'的重复和'.'的任意性,同时满足完全匹配输入字符串的要求。

同步发于 JuzerTech 网站,里面有我软、硬件学习的纪录与科技产品开箱,欢迎进去观看。

题目为给定两个字符串,第二个字符串为字符串格式,比对两字符串是否相符。

' . ' 代表任意单一字符 , ' * ' 代表前一字符可以为0次出现或任意次数出现。

 

题目与范例如下

Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*' where:

'.' Matches any single character.​​​​
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).

Example 1:

Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:

Input: s = "aa", p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
Example 3:

Input: s = "ab", p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".
Example 4:

Input: s = "aab", p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches "aab".
Example 5:

Input: s = "mississippi", p = "mis*is*p*."
Output: false

Constraints:

0 <= s.length <= 20
0 <= p.length <= 30
s contains only lowercase English letters.
p contains only lowercase English letters, '.', and '*'.
It is guaranteed for each appearance of the character '*', there will be a previous valid character to match.

 

解题方法为采用递归策略,如代码所示。

下方为我的代码

bool isMatch(char * s, char * p){
    if(strlen(s) == 0 && strlen(p) == 0){
        return true;
    }
    
    if(strlen(p) > 1 && p[1] == '*'){
        if(isMatch(s,&p[2])){
            return true;
        }
        if((p[0] == '.' || s[0] == p[0]) && strlen(s) > 0){
            return isMatch(&s[1],p);
        }
        return false;
    }
    else{
        if((p[0] == '.' || p[0] == s[0]) && strlen(s) > 0){
            return isMatch(&s[1],&p[1]);
        }
        return false;
    }
    return false;
}

下方为时间与空间之消耗

Runtime: 40 ms, faster than 20.23 % of C online submissions for Regular Expression Matching.

Memory Usage: 5.5 MB, less than 78.61 % of C online submissions for Regular Expression Matching.

本题官方解答还有采用动态规划,可以到 LeetCode上查询。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值