154. 正则表达式匹配

 

154. 正则表达式匹配

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(string s, string p)

 

样例

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 class Solution {
 2 public:
 3     /**
 4      * @param s: A string 
 5      * @param p: A string includes "." and "*"
 6      * @return: A boolean
 7      */
 8     bool isMatchCore(const string &s, int i, const string &p, int j){
 9         if(i==s.size() && j==p.size())return true;
10         if(j==p.size())return false;
11         if(i==s.size()){
12             if(j+1<p.size() && p[j+1]=='*'){
13                 return isMatchCore(s, i, p, j+2);
14             }else return false;
15         }
16         if(j+1<p.size() && p[j+1]=='*'){
17             if(p[j]=='.'){
18                 return isMatchCore(s, i, p, j+2) || isMatchCore(s, i+1, p, j);
19             }else{
20                 if(s[i]==p[j])return isMatchCore(s, i, p, j+2) || isMatchCore(s, i+1, p, j);
21                 else return isMatchCore(s, i, p, j+2);
22             }
23         }else{
24             if(p[j]=='.' || s[i]==p[j])return isMatchCore(s, i+1, p, j+1);
25             else return false;
26         }
27     }
28     bool isMatch(string &s, string &p) {
29         return isMatchCore(s, 0, p, 0);
30     }
31 };

 

posted @ 2018-08-13 16:33  jeysin  阅读(172)  评论(0编辑  收藏  举报