码迷,mamicode.com
首页 > 其他好文 > 详细

Regular Expression Matching

时间:2014-09-09 18:01:59      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   art   div   cti   

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

思路:模仿Wildcard Matching的迭代解法:

 1 class Solution {
 2 public:
 3     bool isMatch( const char *s, const char *p ) {
 4         const char *ds = 0, *dot = 0, *ss = 0, *star = 0;
 5         while( *s != \0 ) {
 6             if( *p == \0 || *(p+1) != * ) {
 7                 if( *s == *p || *p == . ) { ++s; ++p; continue; }
 8                 if( star && *star == *ss ) { s = ++ss; p = star+2; continue; }
 9                 if( dot ) { s = ++ds; p = dot; star = 0; ss = 0; continue; }
10                 return false;
11             } else {
12                 if( *p == . ) {
13                     dot = p+2; ds = s; star = 0; ss = 0;
14                 } else {
15                     if( !star || *p == *s ) { star = p; ss = s; }
16                 }
17                 p += 2;
18             }
19         }
20         while( *p != \0 && *(p+1) == * ) { p += 2; }
21         return *p == \0;
22     }
23 };

网上的递归的解法:

 1 class Solution {
 2 public:
 3     bool isMatch( const char *s, const char *p )
 4     {
 5         assert( s && p );
 6         if( *p == \0 ) { return *s == \0; }
 7         if( *(p+1) != * ) {
 8             assert( *p != * );
 9             return ( (*p == *s) || (*p == . && *s != \0) ) && isMatch( s+1, p+1 );
10         }
11         while( *s == *p || ( *p == . && *s != \0 ) ) {
12             if( isMatch( s, p+2 ) ) { return true; }
13             ++s;
14         }
15         return isMatch( s, p+2 );
16     }
17 };

 

Regular Expression Matching

标签:style   blog   color   io   ar   for   art   div   cti   

原文地址:http://www.cnblogs.com/moderate-fish/p/3960564.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!