Implement regular expression matching with support for
'.'
and'*'
.express'.' 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
定位:困難題spa
題目給出兩種匹配規則,即'.'能匹配任何字符,'*'能夠將前面一個字符重複0到任意次。prototype
此時咱們將'*'與其前一個字符合看爲一個單元考慮。存在如下狀況:code
Java實現:blog
1 public class Solution { 2 public boolean isMatch(String s, String p) { 3 if(p.length()==0){ 4 return s.length()==0; 5 } 6 else if(s.length()==0) { 7 if(p.length()>1&&p.charAt(1)=='*') return isMatch(s, p.substring(2)); 8 else return false; 9 } else if(p.length()>1 && p.charAt(1)=='*') { 10 if(isMatch(s,p.substring(2))) return true; 11 else if(s.charAt(0)==p.charAt(0)||p.charAt(0)=='.') { 12 return isMatch(s.substring(1), p); 13 } else return false; 14 } else { 15 return (s.charAt(0)==p.charAt(0) || p.charAt(0)=='.') && isMatch(s.substring(1), p.substring(1)); 16 } 17 } 18 }