【leetcode】10. (Hard) Regular Expression Matching

题目链接


解题思路:
DP


提交代码:

class Solution {
    public boolean isMatch(String s, String p) {
     	boolean match[][]=new boolean[s.length()+1][p.length()+1];
    	match[0][0]=true;
    	
    	//init row1
    	int flag1=0; //flag1是记录已经连续多少个已经不是‘*’
    	for(int i=0;i<p.length();i++) {
    		if(flag1==0&&p.charAt(i)!='*') {
    			flag1=1;
    			match[0][i+1]=false;
    		}
    		else if(flag1==1&&p.charAt(i)!='*') {
    			for(int j=i+1;j<=p.length();j++)
    				match[0][j]=false;
    			break;
    		}
    		
    		else if(flag1==1&&p.charAt(i)=='*') {
    			flag1=0;
    			match[0][i+1]=true;
    		}
    	}
    	
    	
    	for(int i=0;i<s.length();i++) {
    		for(int j=0;j<p.length();j++) {
    			if(s.charAt(i)==p.charAt(j)||p.charAt(j)=='.') {
    				match[i+1][j+1]=match[i][j];
    			}
    			else if(p.charAt(j)=='*') { 
    				if(match[i+1][j]==true) {
    					match[i+1][j+1]=true;
    					continue;
    				}
    				if(p.charAt(j-1)==s.charAt(i)||p.charAt(j-1)=='.') {
    					match[i+1][j+1]=(match[i][j]||match[i][j+1]);  //.*  and aaa
    					if(match[i+1][j+1]==true)
    						continue;
    				}
    				if((j-2)>=0&&
    			(p.charAt(j-2)==s.charAt(i)||p.charAt(j-2)=='*'||p.charAt(j-2)=='.')) 
    					match[i+1][j+1]=match[i+1][j-1];
    				else
    					match[i+1][j+1]=false;
    			}
    			else
    				match[i+1][j+1]=false;
    		}
    	}
    	
    	
    	
    	return match[s.length()][p.length()];
    }
}


运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/AXIMI/article/details/83927809