http://decomplexify.blogspot.com/2014/04/wildcard-match-star-and-qmark-asymmetric.html
Here is the solution for it.
I cannot find any explanation is better than this.
public boolean isMatch(String s, String p) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
String[] T = p.split("\\*+", -1);
//special case: p has no star
if (T.length == 1) {
return matchedWithQMark(s, p, 0) && s.length()==p.length();
}
String head = T[0];
String tail = T[T.length - 1];
//Special case can't match first and last without overlapping
if (head.length()+tail.length() > s.length() || !matchedWithQMark(s, head, 0) ||
!matchedWithQMark(s, tail, s.length()-tail.length())) {
return false;
}
int n = T.length;
if (n==2) { return true; }
//Do not match the first piece
int start = head.length();
int sLen = s.length() - tail.length();
//index for the next piece
int i=1;
for (; i<T.length - 1; i++) {
int tLen = T[i].length();
boolean found = false;
while (start <= sLen -tLen) {
if (matchedWithQMark(s, T[i], start)) {
found = true;
break;
}
start++;
}
if (!found) {return false;}
//updating the start index
start += tLen;
}
return i>=T.length-1;
}
private boolean matchedWithQMark(String s, String t, int start) {
if (start + t.length() > s.length()) return false;
for (int j=0; start+j < s.length()&& j<t.length();++j) {
if (s.charAt(start+j)!=t.charAt(j) && t.charAt(j)!='?') {
return false;
}
}
return true;
}
No comments:
Post a Comment