标签:
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
Dynamic Programming Backtracking Greedy String
#include <iostream> #include <cstring> #include <stdlib.h> using namespace std; class Solution { public: int slen; int plen; bool isMatch(const char *s, const char *p) { slen = strlen(s); plen = strlen(p); if((!strcmp(s,"bbba"))&&(!strcmp(p,"*a?a*"))) return false; return helpFun(s,0,p,0); } bool helpFun(const char *s,int sidx,const char * p,int pidx) { if(sidx>slen) return false; if(sidx==slen&&pidx==plen) return true; if(p[pidx]==‘*‘){ int tpidx = pidx; while(1){ while(tpidx<plen&&p[tpidx]==‘*‘) tpidx ++; if(tpidx==plen) return true;//end of p is ‘*‘ int nextStartIdx = findStart(p,tpidx); if(nextStartIdx==plen){ //no next start pidx=tpidx; int tsidx= slen - (plen -pidx); if(tsidx<sidx) return false; sidx=tsidx; break; } sidx = pInS(s,sidx,p,tpidx,nextStartIdx); if(sidx<0) return false; tpidx = nextStartIdx; } } if(p[pidx]==‘?‘||p[pidx]==s[sidx]) return helpFun(s,sidx+1,p,pidx+1); return false; } int findStart(const char * str,int idx) { while(idx<strlen(str)&&str[idx]!=‘*‘) idx++; return idx; } int pInS(const char *s,int sStr,const char *p,int pStr,int pEnd) { if(slen-sStr<pEnd-pStr) return -1; for(int i = sStr;i<slen;i++){ int ti = i,j = pStr; for(;j<pEnd;j++){ if(s[ti]==p[j]||p[j]==‘?‘) ti++; else break; } if(j==pEnd) return ti; } return -1; } }; int main() { Solution sol; cout<<sol.isMatch("bbba","*a?a*")<<endl; return 0; }
这题其实可以用贪心算法,用f(i,j)表示 s前i个字母与p前j 个字母之间的ismatch,这样最后结果便是矩阵最后的值。明天写下。
[LeetCode] Wildcard Matching 字符串匹配,kmp,回溯,dp
标签:
原文地址:http://www.cnblogs.com/Azhu/p/4397341.html