[Leetcode] Regular Expression Matching

来源:互联网 发布:深圳淘宝运营助理招聘 编辑:程序博客网 时间:2024/05/15 03:59

题目:

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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true


思路:又是一道很恶心的题,尽管代码写出来很简洁。之所以使用递归是因为*的情况需要回溯,虽然也可以使用两个指针记录回溯位置,但是递归写起来比较简洁 —— 只需要考虑当前状态的匹配情况,然后将后面的判断交给下一层函数进行处理。

需要考虑的匹配项有:若对应字符相等或p的字符为'.',可以直接匹配,同时要判断当p的字符为'.'时,s必须有一个字符可以去匹配,不能为空;当p+1为*字符时,需要判断*对应多个字符的所有情况。


class Solution {public:    bool isMatch(const char *s, const char *p) {        if (*p == '\0') return *s == '\0';        if (*(p + 1) != '*') {            return (*s == *p || (*p == '.' && *s != '\0')) && isMatch(s + 1, p + 1);        } else {            while (*s != '\0' && (*s == *p || *p == '.')) {                if (isMatch(s, p + 2)) return true;                s++;            }            return isMatch(s, p + 2);        }    }};


总结:复杂度为O(mn),最坏情况可能需要不断回溯。

0 0
原创粉丝点击