您的位置:首页 > 其它

leetcode: Regular Expression Matching

2013-10-28 12:20 316 查看
http://oj.leetcode.com/problems/regular-expression-matching/

Implementregularexpressionmatchingwithsupportfor'.'and'*'.

'.'Matchesanysinglecharacter.
'*'Matcheszeroormoreoftheprecedingelement.

Thematchingshouldcovertheentireinputstring(notpartial).

Thefunctionprototypeshouldbe:
boolisMatch(constchar*s,constchar*p)

Someexamples:
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



思路

关键在于'*'的处理。对于类似于"a*"的情况,我们可以匹配0个'a',也可以匹配尽可能多的'a'。

classSolution{
public:
boolisMatch(constchar*s,constchar*p){
if('\0'==*p){
return'\0'==*s;
}

if('*'==*(p+1)){
while((*s!='\0')&&((*s==*p)||('.'==*p))){
if(isMatch(s,p+2)){
returntrue;
}

++s;
}

returnisMatch(s,p+2);
}
else{
if((*s!='\0')&&((*s==*p)||('.'==*p))){
returnisMatch(s+1,p+1);
}

returnfalse;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: