from : https://leetcode.com/problems/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
public class Solution {
public boolean isMatch(String s, String p) {
int i=0, j=0;
int ls = s.length(), lp = p.length();
int statIdx = -1, sIdx = -1;
while(i < ls) {
if(j<lp && (s.charAt(i) == p.charAt(j) || '?' == p.charAt(j))) { //match
++i;
++j;
continue;
}
if(j<lp && '*' == p.charAt(j)) {
statIdx = j; // record star
++j; //match from next p
sIdx = i; // record the position of s , star match 0
continue;
}
if(0 <= statIdx) { //if have star in front then backtrace
j = statIdx + 1; //reset the position of p
i = sIdx + 1;
++sIdx; //star match 1,2,3,4,5....
continue;
}
return false; //if not match return false
}
while(j < lp && '*' == p.charAt(j)) ++j; //skip continue star
return j == lp; // successful match
}
}
class Solution {
public:
bool isMatch(string s, string p) {
int i=0, j=0, ls = s.size(), lp = p.size(), is = -1, jp = -1;
while(i < ls) {
if(j < lp && (s[i] == p[j] || '?' == p[j])) {
++i;
++j;
continue;
}
if(j < lp && '*' == p[j]) {
is = i;
jp = j;
++j;
continue;
}
if(0 <= is) {
++is;
i = is;
j = jp + 1;
continue;
}
return false;
}
while(j < lp && '*' == p[j]) ++j;
return j == lp;
}
};