leetcode No44. Wildcard Matching
来源:互联网 发布:项目进度跟进软件 编辑:程序博客网 时间:2024/06/17 15:59
Question
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
题目大意是:?可以匹配一个字符,*可以匹配多个字符
Algorithm
网上看到的方法:
http://www.cnblogs.com/felixfang/p/3708999.html
摘抄重要的一部分:
以 p = “c*ab*c”,s = “cddabbac”为例。
对于p = “c*ab*c”,我们可以猜想出它可以匹配的s应该长成这样: “c….ab…..c”,省略号表示0到任意多的字符。我们发现主要就是p的中间那个”ab”比较麻烦,一定要s中的’ab’来匹配,因此只要s中间存在一个”ab”,那么一切都可以交给后面的’*’了。
所以说,当我们挨个比较p和s上的字符时,当我们遇到p的第一个’*’,我们实际只需要不断地在s的剩余部分找和’ab’匹配的部分。
换言之,我们可以记录下遇到时p和s的位置,记为presp和press,然后挨个继续比较(++p)和(++s);如果发现*p != *s,就回溯回去,p = presp,s = press+1, ++press;直到比较到末尾,或者遇到了下一个’‘,如果遇到了下一个’‘,说明 “ab”部分搞定了,下面的就交给第二个’‘了;如果p和s都到末尾了,那么就返回true;如果到末尾了既没遇到新的’*’,又还存在不匹配的值,press也已经到末尾了,那么就返回false了。
遇到星号,我们只考虑遇到下一个星号前的子问题,而不是考虑一直到末尾的子问题。从而避免大量的子问题计算。
我们通过记录 prep和pres(初始值为-1),每次回溯的方法,避免使用递归。i,j记录当前遍历s,p的下标。
1、遇到s[i]==p[j]或p[j]==’?’,i++,j++
2、遇到p[j]==星号时,prep记录星号j的下一个元素,pres记录当前i(通配符匹配的起始位置)j++
3、遇到不相等,prep!=-1(说明之前有星号了), i=(++pres);j=prep;
4、否则返回false
while循环后,还要判断p后面的字符是否都是星号
Accepted Code
class Solution {public: bool isMatch(string s, string p) { int i=0,j=0; int pres=-1,prep=-1; while(i<s.size()){ if(j<p.size() && (s[i]==p[j] || p[j]=='?')){ i++; j++; } else if(j<p.size() && p[j]=='*'){ pres=i; prep=++j; } else if(prep!=-1){ i=(++pres); j=prep; } else return false; } while(j<p.size() && p[j]=='*') j++; return j==p.size(); }};
- leetcode No44. Wildcard Matching
- 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
- HTML5的上传文件AJAX方式
- win10怎么配置JDK8的环境变量
- 想学数据分析(人工智能)需要学哪些课程?
- MyBatis关联映射:一对一、一对多
- 【待写】UIPageViewController 如何添加自定义UIViewController
- leetcode No44. Wildcard Matching
- java_高级类修饰符(基本)
- 运算符
- Annotation注解APT(二):自定义注解
- PyCharm运行Scrapy小示例
- java
- PAT(乙级)1012
- 随机打乱和逆过程
- imx6q yocto常见问题