Showing posts with label recursive. Show all posts
Showing posts with label recursive. Show all posts

Wednesday, April 17, 2013

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
public class Solution {     public boolean isMatch(String s, String p) {         return func(s, p, s.length() - 1, p.length() - 1);     }          public boolean func(String s, String p, int i1, int i2){         if(i1 == -1 && i2 == -1){             return true;         }         else if(((i1 < 0 && p.charAt(i2)!='*') || i2 < 0)){             return false;         }                          if(p.charAt(i2) == '.'){             return func(s, p, i1 - 1, i2 -1);         }         else if(p.charAt(i2) == '*'){             i2--;             while(true){                 if(func(s, p, i1, i2 - 1)){                     return true;                 }                 if(i1 < 0 || (s.charAt(i1) != p.charAt(i2) && p.charAt(i2) != '.')){                     break;                 }                 i1--;             }         }         else{             return (s.charAt(i1) == p.charAt(i2)) && func(s, p, i1-1, i2-1);         }                  return false;     }
}