10. Regular Expression Matching

来源:互联网 发布:简洁页面html源码 编辑:程序博客网 时间:2024/06/03 17:17

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、(相应位匹配||模式串为.&&字符串不是\0)&&模式串下一位是*2、(相应位匹配||模式串为.&&字符串不是\0)&&模式串下一位不是*3、相应位不匹配&&(模式位不为.||字符串是\0)对应1,最复杂。分为*取0,*取1,*>=2三种情况。*取0对应跳过当前匹配位,继续寻找patter的下一个匹配位,str不变,pattern+2*取1对应当前匹配位算一次成功匹配,str+1,pattern+2*取>=2对应一次成功匹配,继续匹配字符串的下一位是否匹配,str+1,pattern不变三者取或。即只要有一种情况能匹配成功认为字符串就是匹配成功的。对应2,相当于一次成功匹配,str+1,pattern+1对应3,匹配失败,直接返回false
bool isSubMatch(string& s, int pos1, string& p, int pos2){    if (pos1 == s.size() && pos2 == p.size())return true;    if (pos1 != s.size() && pos2 == p.size())return false;    if (p[pos2 + 1] == '*'){        if (s[pos1] == p[pos2] || (p[pos2] == '.' && pos1 != s.size())){            return isSubMatch(s, pos1, p, pos2 + 2) || isSubMatch(s, pos1 + 1, p, pos2);        }        else            return isSubMatch(s, pos1, p, pos2 + 2);    }    if (s[pos1] == p[pos2] || (p[pos2] == '.' && pos1 != s.size()))        return isSubMatch(s, pos1 + 1, p, pos2 + 1);    return false;}bool isMatch(string s, string p) {    if (s == "" || p == "")return false;    return isSubMatch(s, 0, p, 0);}
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 治安拘留不执行怎么办 释放证明书丢了怎么办 银行提前收贷款怎么办 存货周转天数高怎么办 欠款人没有财产怎么办 起诉后对方没钱怎么办 法院起诉人不到怎么办 治安拘留跑了怎么办 看守所里生病了怎么办 二审上诉被驳回怎么办 醉酒驾车取保候审以后怎么办 小案子证据不足怎么办 撞车不严重逃逸怎么办 被执行人没有财产执行怎么办 挖到人头了怎么办 取保保证金不退怎么办 被诬陷经济诈骗怎么办 醉驾刑事拘留后怎么办 被别人举报赌博怎么办 涉黄刑事拘留怎么办取保候审 换了车牌保险怎么办 车辆转让后保险怎么办 立案后警察不管怎么办 打架后对方讹人怎么办 工商被恶意举报怎么办 店铺被工商举报怎么办 被买单侠恐吓怎么办? 团伙作案刑事拘留怎么办取保 欢乐麻将老输怎么办 回不了家怎么办身份证 没注意闯红灯了怎么办 摩托车被套牌了怎么办? 发现员工偷钱怎么办 盗窃刑事拘留7天怎么办 盗窃抓不到人怎么办 发现宿舍被盗后怎么办(  ) 发现宿舍被盗后怎么办() 回收到赃物电瓶怎么办 不知情买了赃物怎么办 盗窃单位要报警怎么办 上网吸烟被逮住怎么办