Wildcard Matching
Source
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
Java
public class Solution {
public boolean isMatch(String str, String pattern) {
int s = 0, p = 0, preS = -1, preP = -1;
while (s < str.length()){
if (p < pattern.length() && (pattern.charAt(p) == '?' || str.charAt(s) == pattern.charAt(p))){
s++;
p++;
}
else if (p < pattern.length() && pattern.charAt(p) == '*'){
preP = p;
preS = s;
p++;
}
else if (preP != -1){
p = preP + 1;
preS++;
s = preS;
}
else return false;
}
while (p < pattern.length()){
if(pattern.charAt(p)!='*'){
return false;
}
p++;
}
return true;
}
}
Reference
linear runtime and constant space solution
Wildcard Matching