leetcode之通配符
来源:互联网 发布:sql server安装包 编辑:程序博客网 时间:2024/05/22 09:51
Wildcard Matching
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
思路:本题是正常的通配符匹配,可以使用循环,也可以使用递归。使用循环时,每次遇到'*'时,要记录他的位置,这样当匹配失败时,返回到该位置重新匹配。
class Solution {public: bool isMatch(const char *s, const char *p) { const char* sBegin = NULL,*pBegin = NULL; while(*s) { if(*s == *p || *p == '?') { ++s; ++p; } else if(*p == '*') { pBegin = p;//记录通配符的位置 sBegin = s; ++p; } else if(pBegin != NULL) { p = pBegin + 1;//重通配符的下一个字符开始 ++sBegin;//每次多统配一个 s = sBegin; } else return false; } while(*p == '*')++p; return (*p == '\0'); }};
Regular Expression Matching
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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true
思路:本题和上面不同之处在于,此时的通配符'*'和它前面的字符看成一个整体,它们两个代表0到多个第一个字符,而不是任一个字符。所以,当下一个字符是'*'时,如果当前字符相等,则反复跳过当前字符去匹配'*'后面的字符,如果不相等,则直接匹配'*'后面的字符。
class Solution {public: bool isMatch(const char *s, const char *p) { if(*p == '\0')return *s == '\0'; if(*(p+1) != '*') { if(*s != '\0' && (*s == *p || *p == '.'))return isMatch(s+1,p+1); } else { //s向后移动0、1、2……分别和p+2进行匹配 while(*s != '\0' && (*s == *p || *p == '.')) { if(isMatch(s,p+2))return true; ++s; } return isMatch(s,p+2); } return false; }};
4 2
- leetcode之通配符
- LeetCode OJ 之 Wildcard Matching(通配符匹配)
- LeetCode: Wildcard Matching (通配符匹配)
- [LeetCode]44 通配符的匹配
- [leetcode] Wildcard Matching 通配符匹配
- LeetCode-通配符模式串匹配
- 力所能及之struts2通配符
- ant之通配符
- makefile之通配符扩展
- css之通配符选择器
- SQL学习之通配符
- bash之通配符
- Linux学习之通配符
- Linux之文件通配符
- linux之通配符
- Makefile之通配符
- SQL语句之通配符
- bash之通配符
- Java基础之面向对象的基本概念(3)
- php中系统对象的深浅复制
- Android SDK 与API版本对应关系
- Android 系统信息获取(CPU,RAM,ROM,Battery,SD-card,版本等)
- 解决安装vmware-tools出现的“The path "" is not a valid path to the 3.2.0-4-amd64 kernel headers”问题
- leetcode之通配符
- this关键字讲解
- 改造jQuery-Tagit 插件支持中文全角的逗号和空格
- AFNetworking速成教程(1)
- LeetCode-Divide Two Integers
- AFNetworking速成教程(2)
- 每天进步一点点
- 容器常用
- 实现Android 动态加载APK(Fragment or Activity实现)