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") → 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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public boolean isMatch(String s, String p) { 3 int sLen = s.length(); 4 int pLen = p.length(); 5 char [] ss = s.toCharArray(); 6 char [] pp = p.toCharArray(); 7 int str =0, ptr = 0,s1=0,p1=0; 8 boolean star = false; 9 10 for(;str<sLen;str++,ptr++){ 11 if(ptr<pLen&&pp[ptr]=='?'){ 12 continue; 13 } 14 else if(ptr<pLen&&pp[ptr]=='*'){ 15 star = true; 16 s1 = str; 17 p1 = ptr; 18 while(p1<pLen && pp[p1]=='*'){ 19 p1++; 20 } 21 if(p1==pLen) return true; 22 ptr = p1-1; 23 str = s1-1; 24 } 25 else if(ptr == pLen || pp[ptr]!=ss[str]){ 26 if(!star) 27 return false; 28 s1++; 29 ptr = p1-1; 30 str = s1-1; 31 } 32 } 33 while(ptr<pLen&&pp[ptr]=='*'){ 34 ptr++; 35 } 36 return ptr ==pLen; 37 } 38 }