44. Wildcard Matching (String; Recursion)
2015-10-05 19:07
357 查看
Implement wildcard pattern matching with support for
*正则表达式的定义:
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
思路:当遇到*,可能匹配0, 1, 2, ...个字符=>带回溯的递归
'?'and
'*'.
'?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence).不同于正则表达式中的*
*正则表达式的定义:
'.' 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", "*") → true isMatch("aa", "a*") → true isMatch("ab", "?*") → true isMatch("aab", "c*a*b") → false
思路:当遇到*,可能匹配0, 1, 2, ...个字符=>带回溯的递归
class Solution { public: bool isMatch(string s, string p) { star = false; return recursiveCheck(s,p,0,0); } bool recursiveCheck(const string &s, const string &p, int sIndex, int pIndex){ if(sIndex >= s.length()){ while(p[pIndex] == '*' && pIndex < p.length()) pIndex++; //s has went to end, check if the rest of p are all * return (pIndex==p.length()); } if(pIndex >= p.length()){ return checkStar(s,p); } switch(p[pIndex]) //p: pattern,在p中才可能出现?, * { case '?': return recursiveCheck(s, p, sIndex+1, pIndex+1); break; case '*': //如果当前为*, 那么可认为之前的字符都匹配上了,并且将p移动到 * 结束后的第一个字符 star = true; //p 每次指向的位置,要么是最开始,要么是 * 结束的第一个位置 starIndex = pIndex; matchedIndex = sIndex-1; while(p[pIndex] == '*'&& pIndex < p.length()){pIndex++;} //忽略紧接在 *后面的* if(pIndex==p.length()) return true;//最后一位是* return recursiveCheck(s,p,sIndex,pIndex); //*匹配0个字符 break; default: if(s[sIndex] != p[pIndex]) return checkStar(s, p); else return recursiveCheck(s, p, sIndex+1, pIndex+1); break; } } bool checkStar(const string &s, const string &p){ if(!star) return false; else { int pIndex = starIndex+1; int sIndex = ++matchedIndex; //回溯,*d多匹配一个字符 return recursiveCheck(s, p, sIndex, pIndex); } } private: int starIndex; int matchedIndex; bool star; };
相关文章推荐
- iOS编程-------UINavigationController / 界面间通信(传值)
- HDU 4261 Estimation(set预处理中位数+dp+缺页中断t个爽)
- 10.1训练赛--2014上海区域赛--- World Cup**
- 开发人员常用的10个JavaScript库
- 随笔---2015/10/05
- 小宇宙,爆发吧
- 北京Uber优步司机奖励政策(10月5日~10月11日)
- Javascript的异常处理介绍
- Java虚拟机内存模型
- GO 和 KEGG 注释之前,为什么要先进行序列比对(BLAST)?
- 【数据结构】线性结构:存储&运算&时间复杂度
- 把笔记本电脑的无线网络通过网线共享给台式机
- 病毒侵袭---hdu2896(AC自动机)
- JS模拟点击的那些事儿
- ORACLE函数
- Messages: There is no Action mapped for namespace [/] and action name [] associated with context pat
- cocos代码研究(7)即时动作子类学习笔记
- 数据结构之线性表
- google guava io
- KMP