52.正则表达式匹配

题目描述

请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配


思路:首先处理两个指针均属于NULL,此时返回true;其次进行字符串的判断流程,关键点是判断当前所指字符的下一个字符是否为'*'

若是,则进行*匹配的判断,如果char和pattern当前所指字符相匹配(分带‘.’匹配和字母匹配两种),则用递归进行求解(其中有三种匹配形式,分别为0匹配,至少匹配一个字符,只匹配一个字符);如果char和pattern当前所指字符不匹配,则*只能看做0匹配,并进行下一步的递归;

若当前字符的下一个字符不是‘*’,则直接比较char和pattern当前所指字符是否相匹配(分带‘.’匹配和字母匹配两种),若是则递归调用下一步,若不是则返回false;


代码:

class Solution {
public:
    bool match(char* str, char* pattern) {
        if(str == NULL && pattern == NULL)  //deal with the special case
            return true;
        return matchCore(str, pattern);
        
    }
    
    bool matchCore(char* str, char* pattern) {
        if(*str == '\0' && *pattern == '\0')  //match finished
            return true;
        if(*str != '\0' && *pattern == '\0')  //pattern finished and match failed
            return false;
        if(*(pattern + 1) == '*') {  //if pattern pointer next is '*'
            if(*pattern == *str || (*pattern == '.' && *str != '\0'))  //pattern and str matched now
                return matchCore(str + 1, pattern + 2) ||        //'*' used as one char finished, both to next match
                       matchCore(str + 1, pattern) ||            //'*' use as one char at least, str move to next
                       matchCore(str, pattern + 2);              //'*' used as non char, str no move
            else
                return matchCore(str, pattern + 2);              //pattern and str doesn't match now, 
                                                                 //'*' used as non char, str no move
        }
        if(*str == *pattern || (*pattern == '.' && *str != '\0'))
            return matchCore(str + 1, pattern + 1);
        return false;
    }
};

猜你喜欢

转载自blog.csdn.net/nichchen/article/details/80460745