[Leetcode] Wildcard Matching
来源:互联网 发布:python正则表达式替换 编辑:程序博客网 时间:2024/06/06 11:44
题目:
Implement wildcard pattern matching with support for '?'
and '*'
.
'?' Matches any single character.'*' Matches any sequence of characters (including the empty sequence).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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "*") → trueisMatch("aa", "a*") → trueisMatch("ab", "?*") → trueisMatch("aab", "c*a*b") → false
思路:如果没有*的干扰,那么顺序向后比较即可。在*存在时,需要列举*对应多个字符的情况。标记p字符串*后面的第一个非*字符,以及s字符串的当前字符,设为b_s和b_p。当后面发生不匹配时,回溯到这个状态,用b_p去匹配b_s + 1,即,用*去匹配多一个字符。例如abc *c,第一次记录b_s为a,b_p为c,发生不匹配时,回溯,用c去匹配b(这时*去匹配a);再次发生不匹配,回溯,用c去匹配c(这时*去匹配a和b),不断扩大*的作用范围,直到匹配成功,或*匹配完s后面的所有字符而p后面还有非*非?字符。
class Solution {public: bool isMatch(const char *s, const char *p) { const char* backtrack_s = nullptr; const char* backtrack_p = nullptr; while (*s != '\0') { if (*s == *p || *p == '?') { s++; p++; } else if (*p == '*') { while (*p == '*') p++; //move forward until meet the first non-star character if (*p == '\0') return true; //no character left after '*' // record the position of current s // and the first non-star character of p after a sequential '*' backtrack_s = s; backtrack_p = p; } else { //*s != *p && *p != '*' if (backtrack_s == nullptr || backtrack_p == nullptr) return false; s = backtrack_s++; //let '*' to match one more character p = backtrack_p; } } while (*p == '*') p++; return *p == '\0'; }};
总结:复杂度为O(nm),最坏情况可能需要不断回溯。
0 0
- LeetCode: Wildcard Matching
- LeetCode : Wildcard Matching
- [LeetCode] Wildcard Matching - Iteratively
- leetcode 83: Wildcard Matching
- [Leetcode] Wildcard Matching
- [LeetCode]Wildcard Matching
- LeetCode-Wildcard Matching
- LeetCode -- Wildcard Matching
- LeetCode | Wildcard Matching
- Leetcode: Wildcard Matching
- Leetcode:Wildcard Matching
- LeetCode题解:Wildcard Matching
- LeetCode Wildcard Matching
- [Leetcode] Wildcard Matching (Java)
- LeetCode OJ:Wildcard Matching
- Leetcode: Wildcard Matching
- Wildcard Matching -- LeetCode
- [LeetCode] Wildcard Matching
- linux进程优先级、进程nice值
- Android UI 优化——使用HierarchyViewer工具
- Python学习笔记10:标准库之路径和文件(os.path包,glob包)
- 1006 换个格式输出整数 (15)
- JAVA应用在LINUX环境下中文乱码问题处理
- [Leetcode] Wildcard Matching
- str_replace() 函数
- SpringMvc使用Freemarker时的配置文件
- Spring声明式事务配置管理方法
- 《数据结构》间接寻址类的定义参考部分代码
- JAVA注解在SSH开发中的简单应用
- C# Java间进行RSA加密解密交互 .
- openCV常见错误
- 为什么平衡对游戏数值策划如此重要