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
Iteration thru string
public boolean isMatch(String s, String p) {
if (p.indexOf("*") == -1 && p.indexOf("?") == -1) return s.equals(p);
char[] cp = p.toCharArray();
char[] cs = s.toCharArray();
int idx = -1; // store the last index of star appearance
int lastMatch = 0;
int i = 0, j = 0;
while (i < cs.length) {
if (j < cp.length && (cp[j] == '?' || cs[i] == cp[j])) {
i++;
j++;
} else if (j < cp.length && cp[j] == '*') {
idx = j;
lastMatch = i;
j++;
} else if (idx > -1) {
// no match, go back to last time where we saw a star
// or the length of pattern exceeds but the length of string has not
// index of match increases
j = idx + 1;
lastMatch++;
i = lastMatch;
} else return false;
}
while (j < cp.length) {
if (cp[j++] != '*') return false;
}
return true;
}