Wednesday, 11 September 2013

wild card pattern matching algorithm

wild card pattern matching algorithm

i was trying to write code which does a validation for below wildcards:
'?' ------> The question mark indicates there is zero or one of the
preceding element. For example, colou?r matches both "color" and "colour".
'*' ------> The asterisk indicates there is zero or more of the preceding
element. For example, ab*c matches "ac", "abc", "abbc", "abbbc", and so
on.
'+' ------> The plus sign indicates there is one or more of the preceding
element. For example, ab+c matches "abc", "abbc", "abbbc", and so on, but
not "ac".
Can somebody please suggest a better algorithm in terms of time complexity
or innovative (DFA) for this. I know that java does provide pattern
matching with wild cards out of box but this is more of a exercise to
understand the crux by not using libraries. Thanks in advance.
Bug in the code is also welcome. Please find code below:
static boolean matches(String pattern, String text) {
if (text == null && pattern == null) {
return true;
}
if (text == null || pattern == null) {
return false;
}
if (text.equals(EMPTY_STRING) && pattern.equals(EMPTY_STRING)) {
return true;
}
if (text.equals(EMPTY_STRING) || pattern.equals(EMPTY_STRING)) {
return false;
}
char[] p = pattern.toCharArray();
char[] t = text.toCharArray();
int indexP1 = 0, indexP2 = 1, indexT = 0;
while (true) {
if (indexP1 == p.length && indexT == t.length){
return true;
} else if (indexP1 == p.length || indexT == t.length){
return false;
} else {
if (indexP2 < p.length && p[indexP2] == '*'){//case: a*
while (t[indexT] == p[indexP1]) {
indexT++;
if(indexT==t.length)break;
}
indexP1 = indexP1 + 2;
indexP2 = indexP2 + 2;
}
else if (indexP2 < p.length && p[indexP2] == '+') {//case: a+
if(t[indexT] != p[indexP1]){
return false;
}
while (t[indexT] == p[indexP1]) {
indexT++;
if(indexT==t.length)break;
}
indexP1 = indexP1 + 2;
indexP2 = indexP2 + 2;
}
else if (indexP2 < p.length && p[indexP2] == '?') {//case: a?
if (t[indexT] == p[indexP1]) {
indexT++;
}
indexP1 += 2;
indexP2 += 2;
} else {//case: a
if (t[indexT] != p[indexP1]) {
return false;
}
indexP1++;
indexP2++;
indexT++;
}
}
}
}

No comments:

Post a Comment