LeetCode 010 Regular Expression Matching
2014-05-14 14:20
309 查看
【题目】
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
【题意】
题意匹配字符串和正则模式串,只考虑"."和"*"【思路1】
本题与wildcard matching那道题不同,方法不通用本题的关键在于确定每个*需要匹配多少字符
使用DFS方法来做
【代码】
class Solution { public: bool isMatch(const char *s, const char *p) { int sLen=strlen(s); int pLen=strlen(p); if(sLen==0 && pLen==0)return true; if(sLen!=0 && pLen==0)return false; if(sLen==0 && pLen==1)return false; //*都是和一个字符成对出现,p长度为1表明不可能再有* if(p[1]=='*'){ if(p[0]=='.'){ int k=0; //*匹配的字符数 while(k<=sLen){ if(isMatch(s+k, p+2))return true; k++; } } else{ int k=0; //*匹配的字符数 while(k<=sLen && s[k]==p[0]){ if(isMatch(s+k, p+2))return true; k++; } if(isMatch(s+k, p+2))return true; } } else{ if(sLen==0)return false; //注意"" "..*"这种特殊的情况 else if(p[0]=='.' || s[0]==p[0]) return isMatch(s+1, p+1); } return false; } };
相关文章推荐
- [LeetCode]-010-Regular Expression Matching
- leetcode 010 —— Regular Expression Matching(hard)
- leetcode-010:Regular Expression Matching
- leetcode_010 Regular Expression Matching
- 【JAVA、C++】LeetCode 010 Regular Expression Matching
- 2017-09-09 LeetCode_010 Regular Expression Matching
- [LeetCode]010-Regular Expression Matching
- LeetCode 010-Regular Expression Matching
- leetcode--010 Regular Expression Matching
- [LeetCode]题解(python):010-Regular Expression Matching
- [LeetCode]-010-Regular_Expression_Matching
- LeetCode-010 Regular Expression Matching
- LeetCode010 Regular Expression Matching 解析
- leetcode_c++: Regular Expression Matching(010)
- 【LeetCode笔记】Regular Expression Matching
- leetcode第一刷_Regular Expression Matching
- LeetCode - Regular Expression Matching
- [leetcode]Regular Expression Matching
- Leetcode: Regular Expression Matching
- LeetCode Regular Expression Matching