Example
Consideration
- Use two pointer to remember the position of a ‘*’ occurs in the p and the matched position of the string s
- after matching the whole string s, we should continue iterate p to guarantee the ending is matched as well.
Solution
class Solution {
public boolean isMatch(String s, String p) {
int i = 0;
int j = 0;
int lastPosP = -1;
int lastPosS = -1;
while(j < s.length()) {
if(i < p.length() && (s.charAt(j) == p.charAt(i) || p.charAt(i) == '?')) {
++i;
++j;
} else if(i < p.length() && p.charAt(i) == '*') {
//remember the match position and assuming * matches empty string;
lastPosS = j;
lastPosP = i++;
} else if(lastPosS > -1) {
//'*' matches the current character in string s
j = ++lastPosS;
i = lastPosP+1;
} else {
return false;
}
}
while(i < p.length()) {
if(p.charAt(i) != '*') {
break;
}
++i;
}
return i == p.length();
}
}