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);}
阅读全文
0 0
- 10. Regular Expression Matching
- 10.Regular Expression Matching
- 10. Regular Expression Matching
- 10. Regular Expression Matching
- 10. Regular Expression Matching
- 10. Regular Expression Matching
- 10. Regular Expression Matching
- 10. Regular Expression Matching
- 10. Regular Expression Matching
- 10. Regular Expression Matching
- 10. Regular Expression Matching
- 10. Regular Expression Matching
- 10. Regular Expression Matching
- 10. Regular Expression Matching
- 10. Regular Expression Matching
- 10. Regular Expression Matching
- 10. Regular Expression Matching
- 10. Regular Expression Matching
- [python基础理论]python学习笔记2
- Java进阶--Java泛型总结
- GYM 101173 H.Hangar Hurdles(并查集+bfs+dfs)
- Struts2的package的的命名空间(默认命名空间与根命名空间)
- 几条建议,让我们共勉
- 10. Regular Expression Matching
- [bzoj2748][HAOI2012] 音量调节 背包dp
- 《疯狂Java程序员基本修养》笔记(1-5)
- 关于AngularJS中ng-repeat问题(问卷遍历问题)
- onpropertychange与jQuery同时使用时在IE78产生的BUG
- 架构师进击之路一--启航
- 判断一个对象所属类的类型
- log
- J2EE系列之Spring4学习笔记(十)--Spring对JDBC的支持