题目

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”) → 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

分析

字符串匹配问题,有两种解决思路:

  1. 采用递归实现,但是性能不好,TLE;
  2. 贪心解决,参考网址

AC代码

class Solution {
public:
//字符串模式匹配问题,s为匹配串,p为模式串
bool isMatch(string s, string p) {
return isMatch1(s.c_str(), p.c_str());
} /*方法一:采用贪心的性质 AC*/
bool isMatch1(const char *s, const char *p) {
//? match one
//* match 0,1,2,3..
// aaaabc *c true
const char* star = nullptr;
const char* rs = nullptr; while (*s) {
if (*s == *p || *p == '?') { //match
s++; p++;
continue;
}
if (*p == '*') {
star = p; // record star
p++; //match from next p
rs = s; // record the position of s , star match 0
continue;
}
if (star != nullptr) { //if have star in front then backtrace
p = star + 1; //reset the position of p
s = rs + 1;
rs++; //star match 1,2,3,4,5....
continue;
}
return false; //if not match return false
}
while (*p == '*') p++; //skip continue star
return *p == '\0'; // successful match
} /*方法二:利用字符串指针递归解决 性能不好 TLE*/
bool isMatch2(const char *s, const char *p)
{
if (p == NULL || s == NULL)
return false;
else if (*p == '\0')
return (*s == '\0');
else
{
if (*p == '*')
{
while (*p == '*')
++p; /*处理'*'可以匹配任意长度任意格式的字符串*/
while (*s != '\0')
{
if (isMatch2(s, p))
return true;
++s;
}//while return isMatch2(s, p);
}
else if((*s!='\0' && *p == '?') || (*s == *p)){
return isMatch2(++s, ++p);
}//else
return false;
}//else
}
};

GitHub测试程序源码

最新文章

  1. java反射
  2. java内存图解
  3. H5移动端知识点总结
  4. Activity有四种加载模式(转)
  5. dispatchTouchEvent & onInterceptTouchEvent & onTouchEvent
  6. 1_1准备工作[wp8特色开发与编程技巧]
  7. rank() | dense_rank() | row_number() over(PARTITION BY sex order by age desc ) 的区别
  8. C#操作mongodb数据库
  9. python杂乱有关类与对象
  10. 杂谈之SolrCloud这个坑货
  11. HDU-1548--A strange lift--(BFS,剪枝)
  12. 【NO.6】HTTP请求-配置-POST请求-GET请求
  13. Thinking in Java系列 文档+代码+简评
  14. 队列ADT
  15. java的运行机制及初步相关配置(jdk)
  16. Python_Xlrd&Xlwt
  17. ARM 平台下的 SSHD 配置
  18. tinymce与prism代码高亮实现及汉化的配置
  19. jdbc 4.0
  20. python获取前几天的时间

热门文章

  1. 重置 linux系统后要配置的基本组件操作
  2. Java的常量接口思考,项目中的常量是放在接口里还是放在类里呢?
  3. 【转】"超时时间已到。在操作完成之前超时时间已过或服务器未响应"的解决方法
  4. 洛谷P1081 开车旅行70分
  5. WPF 动态加载主题由zip
  6. PHP变量、数据类型、字符串、运算符、条件语句、循环语句、数组、函数
  7. Object类-try-catch-finally-throw-throws-自定义异常
  8. django之分页插件
  9. 如何提高Mysql的查询效率???
  10. IT圈网红,抢鲜围观