Regular Expression Matching
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
思想:如果*(p+1) == '*', 则p可能匹配也可能不匹配;
C++代码:
// char '\0' or 0 a=2,b=a++; b=2;a=3
- bool isMatch(const char *s, const char *p) {
- if( *p == 0) return *s == 0;
- const char *q;
- // q=p++;
- if(*(p+1) != '*') {
- if(*s == *p || (*p == '.' && (*s) != 0)) return isMatch(s+1,p+1);
- else return false;
- } else {
- while(*s == *p || (*p == '.' && (*s) != 0)) {
- if(isMatch(s,p+2)) {
- return true;
- }
- s++;
- }
- return isMatch(s,p+2);
- }
- }
java代码:
- public boolean isMatch(String s, String p) {
- int s1 = s.length();
- int p1 = p.length();
- if(p1==0) return s1==0;
- if(p1==1) return s1==1 && (s.charAt(0)==p.charAt(0) || p.charAt(0)=='.');
- //if(p1==1 && s1>1) return false;
- int i=0;
- int j=0;
- if(p.charAt(j+1) != '*') {
- if(i<s1 && (p.charAt(j) == s.charAt(i) || (p.charAt(j)=='.'))) {
- return isMatch(s.substring(i+1),p.substring(j+1));
- }
- else return false;
- }else {
- while(i<s1 && (p.charAt(j) == s.charAt(i) || (p.charAt(j)=='.'))) {
- if(isMatch(s.substring(i),p.substring(j+2))) {
- return true;
- }
- i++;
- }
- return isMatch(s.substring(i),p.substring(j+2));
- }
- // return false;
- }

浙公网安备 33010602011771号