1. 程式人生 > >【leetcode】10. (Hard) Regular Expression Matching

【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()]; } }

執行結果:
在這裡插入圖片描述