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
def isMatch(s: String, p: String): Boolean = {
if (s.isEmpty) true
else if (p.isEmpty) false
else if (p.length >= 2 && p(1) == '*') {
if (p.head == '.' || s.head == p.head) {
isMatch(s.tail, p.substring(2)) || isMatch(s.tail, p)
}
else isMatch(s, p.substring(2))
}
else {
if (p.head == '.' || s.head == p.head) {
isMatch(s.tail, p.tail)
}
else false
}
}
isMatch("aa", "a")
isMatch("aa", "aa")
isMatch("aaa", "aa")
isMatch("aa", "a*")
isMatch("aa", ".*")
isMatch("ab", ".*")
isMatch("aab", "c*a*b")
Last updated