10、Regular Expression Matching

来源:互联网 发布:中国对东盟投资数据 编辑:程序博客网 时间:2024/05/17 06:54

题目:

mplement 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
解题思路:

python版本:

class Solution(object):    def isMatch(self, s, p):        """        :type s: str        :type p: str        :rtype: bool        """        return re.match('^' + p + '$', s)!=None
c++版本:

class Solution {public:    bool isMatch(string s, string p) {        // both s and p reach their ends        if ( p.empty() ) return s.empty();        // p's next is not *        if ( p[1]!='*' )        {            return ( s[0]==p[0] || (p[0]=='.' && !s.empty()) ) && Solution::isMatch(s.substr(1), p.substr(1));        }        // p's next is * and curr s match curr p        int i = 0;        for ( ; s[i]==p[0] || (p[0]=='.' && i<s.size()); ++i)        {            if ( Solution::isMatch(s.substr(i), p.substr(2)) ) return true;         }        // p's next is * but curr s not match curr p        return Solution::isMatch(s.substr(i), p.substr(2));        }};



0 0
原创粉丝点击