Implement regular expression matching with support for '.'
and '*'
.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 public class Solution { 2 public boolean isMatch(String s, String p) { 3 int mem[][] = new int [s.length()+1][p.length()+1]; 4 return match(s,0,p,0,mem); 5 } 6 public boolean match(String s,int is,String p,int ip,int[][]mem){ 7 if(ip>=p.length())return is==s.length(); 8 if(mem[is][ip]!=0) return mem[is][ip]==1; 9 if(ip<p.length()-1 && p.charAt(ip+1)=='*'){ 10 while(ip<p.length() && is<s.length() && (s.charAt(is)==p.charAt(ip)||p.charAt(ip)=='.')){ 11 if(match(s,is,p,ip+2,mem)){ 12 mem[is][ip] = 1; 13 return true; 14 } 15 is++; 16 } 17 return match(s,is,p,ip+2,mem); 18 } 19 else if(ip<p.length() && is<s.length() && (s.charAt(is)==p.charAt(ip)||p.charAt(ip)=='.')){ 20 return match(s,is+1,p,ip+1,mem); 21 } 22 else{ 23 mem[is][ip]=-1; 24 return false; 25 } 26 27 } 28 }