Easy recursive solution


  • 0
    R
        public boolean isMatch(String s, String p) {
            if(p.isEmpty()) return s.isEmpty();
            
            if(p.length() >= 2 && p.charAt(1) == '*') {
                for(int i = 0; i < s.length() && (p.charAt(0) == '.' || p.charAt(0) == s.charAt(i)); i++) {
                    if(isMatch(s.substring(i+1), p.substring(2))) {
                        return true;
                    }
                }
                
                return isMatch(s, p.substring(2));
            }
           
           return   !s.isEmpty() &&
                    (p.charAt(0) == '.' || p.charAt(0) == s.charAt(0)) && 
                    isMatch(s.substring(1), p.substring(1));
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.