[leetcode-44]Wildcard Matching(c)
来源:互联网 发布:问卷调查报告数据分析 编辑:程序博客网 时间:2024/06/06 11:42
问题描述:
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
分析:最开始这道题的思路就是递归,因为我之前做个与此类似的题就是用的递归,但是很不幸,递归会超时。
后来,看到了网上的一些大牛的做法,他们提到用贪心算法(我感觉很奇怪),其实就是把递归用平常的方式实现了一下。通过保留两个临时变量ss,pp,ss是当出现时,s出现的位置,而pp是出现’‘时p的位置。
当第一次出现时,默认代表字符串长度为0,此时,s不变,p+1,当这种方式出错时,检查是否前面出现过,如果出现过,则s=ss+1,且将ss的指针向前挪1,此时,相当于*代表长度为1。依次类推。
代码如下:TLE
bool solve(char *s,int sLength,int sIndex,char *p,int pLength,int pIndex){ if(sLength<=sIndex||pLength<=pIndex){ if(sLength==sIndex&&pLength==pIndex) return true; return false; } if(p[pIndex]=='?') return solve(s,sLength,sIndex+1,p,pLength,pIndex+1); else if(p[pIndex]=='*'){ while(pIndex>0&&pIndex<pLength&&p[pIndex]==p[pIndex-1]) pIndex++; if(pIndex==pLength) return true; for(int i = 0;i<sLength-sIndex+1;i++){ if(solve(s,sLength,sIndex+i,p,pLength,pIndex+1)) return true; } return false; }else{ if(p[pIndex]!=s[sIndex]) return false; return solve(s,sLength,sIndex+1,p,pLength,pIndex+1); }}bool isMatch(char *s,char *p){ int sLen = strlen(s); int pLen = strlen(p); return solve(s,sLen,0,p,pLen,0);}
代码如下:8ms
bool isMatch(char *s,char *p){ char *ss = NULL; char *pp = NULL; while(*s){ if(*p=='?'){s++;p++;} else if(*p=='*'){ss = s;pp = p++;} else{ if(*s==*p){s++;p++;} else{ if(!ss) return false; s = ss+1; ss = s; p = pp+1; } } } while(*p=='*') p++; return *p=='\0';}
- [leetcode-44]Wildcard Matching(c)
- 【LeetCode】【C++】Wildcard Matching
- LeetCode(44) Wildcard Matching
- [leetcode] 44 Wildcard Matching
- LeetCode 44:Wildcard Matching
- leetcode 44: Wildcard Matching
- leetcode 44: Wildcard Matching
- [leetcode 44] Wildcard Matching
- leetcode 44:Wildcard Matching
- LeetCode 44 - Wildcard Matching
- leetcode 44 Wildcard Matching
- LeetCode(44) Wildcard Matching
- LeetCode 44 Wildcard Matching
- Leetcode (44) Wildcard Matching
- leetcode(44) - Wildcard Matching
- 【leetcode 44】Wildcard Matching
- LeetCode 44 Wildcard Matching
- Leetcode 44:Wildcard Matching
- 信号槽
- Linux-nginx-phpfpm
- ScrollView 和 ListView的兼容解决
- hdu 5339 Untitled【搜索】
- php踩坑记录(持续更新)
- [leetcode-44]Wildcard Matching(c)
- 欢迎使用CSDN-markdown编辑器
- HDU-4217(树状数组)
- Nginx实现多个站点使用一个端口(配置Nginx的虚拟主机)
- 一个Netfilter nf_conntrack流表查找的优化-为conntrack增加一个per cpu cache
- 解决Cmder无法在Windows Xp下运行的问题
- http封装
- CentOS LNMP环境搭建
- 【剑指Offer面试题】 九度OJ1524:复杂链表的复制