首页 > 其他 > 详细

LeetCode OJ:Regular Expression Matching(正则表达式匹配)

时间:2015-11-23 23:27:35      阅读:277      评论:0      收藏:0      [点我收藏+]

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

正则表达式的匹配,注意*代表的不是任意的字符,而是0个或者任意多个前向的字符,代码如下:

 1 class Solution {
 2 public:
 3     bool isMatch(string s, string p) {
 4            if(p.size() == 0) return s.size() == 0;
 5            if(p[1] != *){
 6                if(s.size() != 0 && (p[0] == s[0] || p[0] == .)) 
 7                    return isMatch(s.substr(1), p.substr(1));
 8                return false;
 9            }else{
10                while(s.size() != 0 &&(s[0] == p[0] || p[0] == .)){//模式串匹配0个或者更多的字符
11                    if(isMatch(s, p.substr(2)))
12                        return true;
13                    s = s.substr(1);
14                }
15                return isMatch(s, p.substr(2));
16            }
17     }
18 };

 

LeetCode OJ:Regular Expression Matching(正则表达式匹配)

原文:http://www.cnblogs.com/-wang-cheng/p/4987594.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!