Leetcode Regular Expression Matching problem solution in Java programming

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,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *