[LeetCode]—Regular Expression Matching 正则匹配
Regular Expression Matching Implement regular expression matching with support for '.' 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
问题的难点主要在处理“*”问题上,LeetCode给出了解题思路: http://leetcode.com/2011/09/regular-expression-matching.html Solution: A natural way is to use a greedy approach; that is,we attempt to match the previous character as many as we can. Does this work? Let us look at some examples. s= “abbbc”,p= “ab*c” s= “ac”,p= “ab*c” It seems that being greedy is good. But how about this case? s= “abbc”,p= “ab*bbc” One might be tempted to think of a quick workaround. How about counting the number of consecutive b’s ins? If it is smaller or equal to the number of consecutive b’s after “b*” inp,we conclude they both match and continue from there. For the opposite,we conclude there is not a match. This seem to solve the above problem,but how about this case: Here,“.*” inpmeans repeat ‘.’ 0 or more times. Since ‘.’ can match any character,it is not clear how many times ‘.’ should be repeated. Should the ‘c’ inpmatches the first or second ‘c’ ins? Unfortunately,there is no way to tell without using some kind of exhaustive search. We need some kind of backtracking mechanism such that when a matching fails,we return to the last successful matching state and attempt to match more characters inswith ‘*’. This approach leads naturally to recursion. The recursion mainly breaks down elegantly to the following two cases:
You would need to consider the base case carefully too. That would be left as an exercise to the reader. 给出参考解法:class Solution { public: bool isMatch(const char *s,const char *p) { assert( s && p); if(*p==' ') return *s==' '; if(*(p+1)!='*'){ if(*p==*s || (*p=='.' && *s!=' ')) return isMatch(s+1,p+1); else return false; }else{ while(*p==*s || *p=='.' && *s!=' '){ if(isMatch(s,p+2)) return true; s++; } return isMatch(s,p+2); } } }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |