In the Leetcode Regular Expression Matching problem solution in Java programming Given an input string s and a pattern p, implement regular expression matching with support for ‘.’ and ‘*’ where:
‘.’ Matches any single character.
‘*’ Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Leetcode Regular Expression Matching problem solution in Java programming
class Solution {
public boolean isMatch(String s, String p) {
return isMatch(s,p,'\0');
}
private boolean isMatch(String s,String p,char pred){
if(s.length()==0){
if(p.length()==0)
return true;
if(pred!='\0'){
return isMatch(s,p.substring(1),'\0');
}
else if(p.length()>1 && p.charAt(1)=='*'){
return isMatch(s,p.substring(2),'\0');
}
else
return false;
}
else if(p.length()==0)
return false;
else if(pred!='\0'){
if(s.charAt(0)==pred || pred=='.'){
return isMatch(s.substring(1),p,pred) || isMatch(s,p.substring(1),'\0');
}
else
return isMatch(s,p.substring(1),'\0');
}
else if(p.length()>1 && p.charAt(1)=='*'){
return isMatch(s,p.substring(1),p.charAt(0));
}
else if(s.charAt(0)==p.charAt(0) || p.charAt(0)=='.'){
return isMatch(s.substring(1),p.substring(1),'\0');
}
else
return false;
}
}
Also read,
- Leetcode Regular Expression Matching problem solution in C++
- Leetcode Regular Expression Matching problem solution in C
- Leetcode Regular Expression Matching problem solution in Python
- Leetcode Regular Expression Matching problem solution in C#