Java explanation with example


  • 0

    We need to check three conditions based on p:

    • p is "" // p is empty.

    • p is "whatsoever" // the second character is not *.

    • p is "[a-z.]*whatsoever" // the second character is *.

    public class Solution {
        public boolean isMatch(String s, String p) {
            if(p.length()==0) return s.length()==0;
            // e.g  s:"a"    p:""
    
            if(p.length()==1 || p.charAt(1)!='*'){
                if(s.length()==0) return false;
                // e.g  s:""    p:"abc"    
    
                if(p.charAt(0)==s.charAt(0) || p.charAt(0)=='.'){
                    return isMatch(s.substring(1), p.substring(1));
                    // e.g  s:"abc"    p:"awhatsoever" or ".whatsoever"
                }else{
                    return false;
                    // e.g  s:"a"    p:"bwhatsoever"
                }
            }
            
            for(int i=0;i<s.length();++i){
                if(p.charAt(0)=='.' || s.charAt(i)==p.charAt(0)){
                    if(isMatch(s.substring(i+1), p.substring(2)))
                        return true;
                    // e.g  s:"aabcd"    p:"a*whatsoever"
                }else{
                    break;
                }
            }
            return isMatch(s, p.substring(2));
            // e.g  s:"aac"    p:"b*whatsoever"
        }
    }
    
    

Log in to reply
 

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