I created an algorithm to check matching strings given that some characters might be a regular expression defined by '*', or '.' I'm trying to analyze its complexity; however I can't see what the Big O for this recursive function really is.
The algorithm takes 2 strings as input, and returns a boolean if one string can be matched by the second or vice-versa.
Example:
A = "abc"
B = "ab*"
Output = true
A = "ab."
B = "abc"
Output = true
A = "abcd*"
B = "ab"
Output = false
public static boolean match(String a, String b) {
//Check if a == b , if so, strings match
if (a.equals(b))
return true;
//Check if second char in a in an asterisk, return true if substring of b matches b.
if (hasAsterisk(a) && match(a.substring(2), b))
return true;
//Check if second char of b is an asterisk, return true if substring of b matches a.
if (hasAsterisk(b) && match(a, b.substring(2)))
return true;
//Check if a and b is not empty
if (!a.isEmpty() && !b.isEmpty()) {
//Check if first char of a is asterisk, if so match a substring with b
if (a.charAt(0) == '*')
return match(a.substring(1), b);
//Check if first char of b is asterisk, if so match b substring with a
if (b.charAt(0) == '*')
return match(a, b.substring(1));
//Check if first char of a or b is "DOT(.)", if so match substrings.
return charMatch(a.charAt(0), b.charAt(0))
&& match(a.substring(1), b.substring(1));
}
//If not match, return false
else
return false;
}
private static boolean hasAsterisk(String a) {
return a.length() > 1 && a.charAt(1) == '*';
}
private static boolean charMatch(char a, char b) {
return a == b || a == '.' || b == '.';
}
My follow up question is, how can this run more efficiently?
Thank you!