10. Regular Expression Matching
阿新 • • 發佈:2017-09-22
ret pan style match clas length charat color pre
Recursive
class Solution { public boolean isMatch(String s, String p) { return isMatch(s, 0, p, 0); } public boolean isMatch(String s, int i, String p, int j) { if(i==s.length()&&j==p.length()) return true; if(i>s.length()||j>=p.length())return false; if(j+1<p.length()&&p.charAt(j+1)==‘*‘) { boolean ret=isMatch(s,i,p,j+2); if(i<s.length()&&(p.charAt(j)==‘.‘||s.charAt(i)==p.charAt(j))) ret=ret||isMatch(s,i+1,p,j); return ret; }if(i<s.length()&&(p.charAt(j)==‘.‘||s.charAt(i)==p.charAt(j))) return isMatch(s,i+1,p,j+1); return false; } }
DP
//isMatch(p,i,s,j) //if(p[i]==s[j]||p[i]==‘.‘) isMatch(p,i-1,s,j-1) //if(p[i]==‘*‘) isMatch(p,i-2,s,j) //if(p[i]==‘*‘&&(p[i-1]==s[j]||p[i-1]==‘.‘) isMatch(p,i-1,s,j)||isMatch(p,i,s,j-1)class Solution { public boolean isMatch(String s, String p) { boolean[][] dp=new boolean[p.length()+1][s.length()+1]; dp[0][0]=true; for(int i=1;i<=p.length();i++) for(int j=0;j<=s.length();j++) dp[i][j]=j>0&&(p.charAt(i-1)==s.charAt(j-1)||p.charAt(i-1)==‘.‘)&&dp[i-1][j-1] ||p.charAt(i-1)==‘*‘&&i>1&&dp[i-2][j] ||p.charAt(i-1)==‘*‘&&i>1&&j>0&&(p.charAt(i-2)==s.charAt(j-1)||p.charAt(i-2)==‘.‘)&&(dp[i-1][j]||dp[i][j-1]); return dp[p.length()][s.length()]; } }
10. Regular Expression Matching