您的位置:首页 > 其它

LeetCode "Regular Expression Matching"

2014-08-12 05:05 369 查看
It took me numerous submissions to get AC.... until I checked this article:
http://leetcode.com/2011/09/regular-expression-matching.html
Very clean idea. Again, think crystal clean before you code!!

class Solution {
public:
struct Rec
{
Rec(char cc, bool bStar) : c(cc), star(bStar) {}
char c;
bool star;
};
bool _isMatch(string &s, int i0, vector<Rec> &dict, int i1)
{
if(i1 == dict.size()) return i0 == s.length();

char c = s[i0];
Rec &r = dict[i1];
if (!r.star)    //    Not Star
{
return (c == r.c || r.c == '.') && _isMatch(s, i0 + 1, dict, i1 + 1);
}
// star
while(c == r.c || r.c == '.')
{
if (_isMatch(s, i0, dict, i1 + 1)) return true;
if(i0 < s.length())
c = s[++ i0];
else break;
}
//     even not match star?
return _isMatch(s, i0, dict, i1 + 1);
}
bool isMatch(const char *s, const char *p) {
int len1 = strlen(s);
int len2 = strlen(p);
if(len1 == 0 && len2 == 0) return true;
if(len2 == 0) return false;

//    Build pattern
vector<Rec> dict;
for(size_t i = 0; i < len2; i ++)
{
char c = *(p + i), nc = 0;
if(c == '*')
{
continue;
}

if((i + 1) < len2)    nc = *(p + i + 1);
dict.push_back(Rec(c, nc == '*'));
}
if(len1 == 0)
{
int i = 0;
while(i < dict.size())
if(!dict[i++].star) return false;
return true;
}
string str(s);
return _isMatch(str, 0, dict, 0);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: