public class Solution {
public boolean isMatch(String s, String p) {
int i = 0, j = 0;
// p.charAt(j) == '*', sAsterisk = i, pAsterisk = ++j
int sAsterisk = 0, pAsterisk = 0;
while(i < s.length()) {
if(j < p.length() && (p.charAt(j) == '?' || s.charAt(i) == p.charAt(j))) {
i++;
j++;
} else if(j < p.length() && p.charAt(j) == '*') {
sAsterisk = i;
pAsterisk = ++j;
} else if(pAsterisk != 0) {
i = ++sAsterisk;
j = pAsterisk;
} else {
return false;
}
}
// Checks if the rest chars of p are all '*'
while(j < p.length() && p.charAt(j) == '*') {
j++;
}
return j == p.length();
}
}
Time: O(m * n)
Space: O(1)