Sunday, August 21, 2016

Strings LeetCode – Regular Expression Matching in Java

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") return false
isMatch("aa","aa") return true
isMatch("aaa","aa") return false
isMatch("aa", "a*") return true
isMatch("aa", ".*") return true
isMatch("ab", ".*") return true
isMatch("aab", "c*a*b") return true
I had referred below link to understand the solution and implement.
Below is the solution (The only difference is i did not use the substring but used an index to traverse the string)
public static boolean patternMatch(String text,String pattern,int tIndex,int pIndex)
{
//if the pattern length is zero then condition passes if only string length is also zero 
if(pIndex>=pattern.length())
{
return tIndex == text.length();
}
if(pIndex+1==pattern.length() || pattern.charAt(pIndex+1)!='*')
{
if(tIndex>=text.length() && pattern.charAt(pIndex)!='.' &&     pattern.charAt(pIndex)!=text.charAt(tIndex))
{
return false;
}
else
{
return patternMatch(text,pattern,tIndex+1,pIndex+1);
}
}
else
{
int i = -1;
while(tIndex+i<text.length() &&  (i<0||pattern.charAt(pIndex)=='.'||pattern.charAt(pIndex)==text.charAt(tIndex+i)))
{
if(patternMatch(text, pattern, tIndex+i+1, pIndex+2))
{
return true;
}
i++;
}
}
return false;
}





No comments:

Post a Comment