题目描述: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 }