[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
题意:
实现字符串的正则匹配,’.’能够匹配任意字符,’*’能够代替0个或者多次它前面的字符。
思路:
使用回溯的方法,主要需要考虑的是’‘,如果当前字符的下一个字符是’ ‘的话,那么当前字符可以匹配0次,或者1次或者多次。我们使用两个下标i,j指向源串与目标串的下次需要匹配的位置。那么当j+1指向的是’ * ‘的话,那么我们可以匹配0次,即让第二个指示器往后移动两个到j+2,i不变。或者匹配一次,i往后移动一位,而j不变,这样由于j后面的还是’ *’,所以还可以匹配j的0或者多次。
以上。
代码如下:

class Solution {
public:
    bool isMatch(string s, string p) {
        this->s = s;
        this->p = p;
        sLen = s.length();
        pLen = p.length();
        return isMatch(0, 0);
    }
    bool isMatch(int i, int j) {
        if (i == sLen && j == pLen)return true;
        else if (j == pLen)return false;
        else if (i > sLen) {
            return false;
        }
        if (j != pLen - 1 && p[j + 1] == '*') {
            bool result = isMatch(i, j + 2) || ((s[i] == p[j] || p[j] == '.') && isMatch(i + 1, j));
            return result;
        }
        else if (s[i] == p[j] || p[j] == '.') {
            return isMatch(i + 1, j + 1);
        }
        else return false;
    }
private:
    string s;
    string p;
    int sLen;
    int pLen;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值