題目描述:express
Implement regular expression matching with support for '.'
and '*'
.spa
'.' Matches any single character. '*' Matches zero or more of the preceding element.
解題思路:code
這道題若是隻考慮「.」的話其實很好完成,因此解題的關鍵在於處理「*」的狀況。覺得「*」與前一個字母有關,因此應該總體考慮ch*……的狀況。ch*能夠匹配0-n個s的字符串,(n是s的起始位置開始值爲ch的字符的個數)。固然還要考慮.*……的狀況,這樣的狀況系,就要考慮把.*與s的全部字符都匹配一遍,看能不能找出結果。其餘的考慮狀況比較容易想到,看下面的代碼便可。blog
具體代碼:遞歸
1 public static boolean isMatch(String s, String p) { 2 //p爲null或者長度爲0的狀況 3 if(p==null){ 4 return s==null; 5 } 6 if(p.length()==0){ 7 return s.length()==0; 8 } 9 if(p.length()==1){ 10 if(s.length()!=1){ 11 return false; 12 } 13 else{ 14 if(p.charAt(0)=='.'){ 15 return true; 16 } 17 else if(p.charAt(0)=='*'){ 18 return false; 19 } 20 else{ 21 return p.charAt(0)==s.charAt(0); 22 } 23 } 24 } 25 //p至少有長度爲2 26 if(p.contains("*")|| p.contains(".")){ 27 //ch*狀況的處理 28 if(p.charAt(1)=='*'){ 29 char ch = p.charAt(0); 30 //.*的狀況,.*能夠匹配s的任意個字符,因此把每種可能的狀況遞歸一遍 31 if(ch=='.'){ 32 for(int i=0;i<=s.length();i++){ 33 boolean key = isMatch(s.substring(i), p.substring(2)); 34 if(key==true) 35 return true; 36 } 37 } 38 //ch*的狀況,ch*能夠匹配0-n個s的字符串,(n是s的起始位置開始值爲ch的字符的個數) 39 else{ 40 int index=0; 41 while(index<s.length() && s.charAt(index)==p.charAt(0)){ 42 index++; 43 } 44 for(int i=0;i<=index;i++){ 45 boolean key = isMatch(s.substring(i), p.substring(2)); 46 if(key==true) 47 return true; 48 } 49 } 50 } 51 //不是ch*的狀況,即chch……的狀況,這時候s的長度要保證大於0 52 else{ 53 if(p.charAt(0)=='.'){ 54 if(s.length()==0){ 55 return false; 56 } 57 boolean key = isMatch(s.substring(1), p.substring(1)); 58 return key; 59 } 60 else{ 61 if(s.length()==0){ 62 return false; 63 } 64 //若是開頭字符相等,匹配與否取決於兩字符串除去第一個字符後是否匹配 65 if(p.charAt(0)==s.charAt(0)){ 66 boolean key = isMatch(s.substring(1), p.substring(1)); 67 return key; 68 } 69 else{ 70 return false; 71 } 72 } 73 } 74 75 return false; 76 } 77 //p不包含*,.的狀況 78 else{ 79 if(s.equals(p)) 80 return true; 81 return false; 82 } 83 }