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", "ca*b") → true
public class Solution {
public boolean isMatch(char []s, int sIndex, char[] p, int pIndex){
int sLen = s.length;
int pLen = p.length;
if(sIndex == sLen && pIndex == pLen){
return true;
}else if(sIndex != sLen && pIndex == pLen){
return false;
}
//else pIndex != pLen
if(pIndex+1 < pLen && p[pIndex + 1] == '*'){
if(sIndex == sLen){
return isMatch(s, sIndex, p, pIndex+2);
}
if(p[pIndex] == '.'){
if(isMatch(s, sIndex+1, p, pIndex)){
return true;
}else{
return isMatch(s, sIndex, p, pIndex+2);
}
}else{
if(s[sIndex] == p[pIndex]){
if(isMatch(s, sIndex+1, p, pIndex)){
return true;
}else{
return isMatch(s, sIndex, p, pIndex+2);
}
}else{
return isMatch(s, sIndex, p, pIndex+2);
}
}
}else{
if(sIndex < sLen && (p[pIndex] == '.' || p[pIndex] == s[sIndex])){
return isMatch(s, sIndex+1, p, pIndex+1);
}else{
return false;
}
}
}
public boolean isMatch(String s, String p) {
char [] sc = s.toCharArray();
char [] pc = p.toCharArray();
return isMatch(sc, 0, pc, 0);
}
}
网友评论