Thursday, September 8, 2016

LeetCode Online Judge-10. Regular Expression Matching

Implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.

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", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true

Tell you a secret. I initially added only 1 line and it was accepted!
Well, that's "return s.matches(p);" in Java. Ha-ha!

OK, I did know this answer was not expected for training.
So here comes my recursive program.

//Java Program: Regular Expression Matching
public class Solution {
    public boolean isMatch(String s, String p) {

if (p.length()==0) {
if (s.length()==0) {
return true;
} else {
return false;
}
}

if (p.length()==1) {
if (s.length()==1&&(p.charAt(0)=='.'||s.charAt(0)==p.charAt(0))) {
return true;
}
return false;
}

if (s.length()>0&&p.length()>0&&(p.charAt(p.length()-1)=='.'||s.charAt(s.length()-1)==p.charAt(p.length()-1))) {
return isMatch(s.substring(0, s.length()-1), p.substring(0, p.length()-1));
}

if (p.length()>1&&p.charAt(p.length()-1)=='*') {
if (s.length()==0) {
return isMatch(s, p.substring(0, p.length()-2));
}
if (p.charAt(p.length()-2)!='.'&&s.charAt(s.length()-1)!=p.charAt(p.length()-2)) {
return isMatch(s, p.substring(0, p.length()-2));
}
if (isMatch(s, p.substring(0, p.length()-2))) {
return true;
}
if (isMatch(s.substring(0, s.length()-1), p.substring(0, p.length()-2))) {
return true;
}
return isMatch(s.substring(0, s.length()-1), p);
}

return false;

    }
}