Java code,how to improve it


  • 0
    X
    public class Solution {
    public boolean isMatch(String s, String p) {
        if(s == null && p == null) 
            return true;
        if(s == null || p == null)
            return false;
        int slen = s.length(),plen = p.length();
        for(int i = 0,j = 0; i < slen && j < plen;){
            if(j + 1 < plen && p.charAt(j+1) == '*'){
                if(!isMatchFirst(s.substring(i),p.substring(j))){
                    if(j + 2 < plen && isMatch(s.substring(i),p.substring(j+2)))
                        return true;
                    return false;
                }
                else{
                    if(i + 1 == slen && j + 2 == plen && p.charAt(j+1) == '*')
                        return true;
                    if(i + 1 < slen && j + 2 < plen && isMatch(s.substring(i+1),p.substring(j+2)))
                        return true;
                    if(j + 2 < plen && isMatch(s.substring(i),p.substring(j+2)))
                        return true;
                    if(i + 1 < slen && isMatch(s.substring(i+1),p.substring(j)))
                        return true;
                    return false;
                }
            }
            else{
                if(isMatchFirst(s.substring(i),p.substring(j))){
                    i++;
                    j++;
                    if(i == slen && (j == plen || j + 2 == plen && p.charAt(j+1) == '*'))
                        return true;
                }
                else
                    return false;
            }
        }
        return false;
    }
    
    public boolean isMatchFirst(String s,String p){
        if(s.charAt(0) == p.charAt(0)||p.charAt(0) == '.')
            return true;
        return false;
    }
    

    }

    Time Limit Exceeded
    Last executed input: "aaaaaaaaaaaaab", "aaaaaaaaaac"
    I proved it's false,but consumed 12157ms...
    anyone solved it with java?


Log in to reply
 

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