aiheshan

有多自律,才能有多自由

导航

leetcode 10. Regular Expression Matching

https://leetcode.com/problems/regular-expression-matching/

题目:正则表达式匹配。

'.':匹配任意字符;

'*':匹配0个或者多个前一个字符;

 由例子可知道。"ab",".*"->true; 可知当*前面为.时,则相当于与匹配任意0或多个字符。

思路:采用递归的方法,当s.length()=0时,可能返回true的p只能为"a*b*..";因为a*可匹配0字符。

当p.length()=0,s也必须为0;

因为a* 可匹配0字符,所以p[1]='*', 递归判断isMatch(s,p.substr(2)) ;a* 匹配1个以上字符,则isMatch(s.substr(1),p);

当p[0]='.' || p[0]==s[0],则匹配一个s字符,递归判断isMatch(s.substr(1),p.substr(1))

 1 class Solution {
 2 public:
 3     bool isMatch(string s, string p) {
 4       if(p.length()==0) {
 5           return s.length()==0;
 6       }
 7       else if(s.length()==0){
 8           if(p.length()>1&&p[1]=='*') return isMatch(s,p.substr(2));
 9           else return false;
10       }
11       else if(p.length()>1&&p[1]=='*') {
12           if(isMatch(s,p.substr(2)))
13             return true;
14           if(p[0]=='.'||p[0]==s[0])
15             return isMatch(s.substr(1),p);
16         return false;
17       }
18       else if(p[0]=='.'||p[0]==s[0]) return isMatch(s.substr(1),p.substr(1));
19       return false;
20     }
21 };

 

posted on 2016-08-16 00:28  aiheshan  阅读(215)  评论(0编辑  收藏  举报