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

  1. bool isMatch(const char *s, const char *p) {
  2. if( *p == 0) return *s == 0;
  3. const char *q;
  4. // q=p++;
  5. if(*(p+1) != '*') {
  6. if(*s == *p || (*p == '.' && (*s) != 0)) return isMatch(s+1,p+1);
  7. else return false;
  8. } else {
  9. while(*s == *p || (*p == '.' && (*s) != 0)) {
  10. if(isMatch(s,p+2)) {
  11. return true;
  12. }
  13. s++;
  14. }
  15. return isMatch(s,p+2);
  16. }
  17. }

java代码:

  1. public boolean isMatch(String s, String p) {
  2. int s1 = s.length();
  3. int p1 = p.length();
  4. if(p1==0) return s1==0;
  5. if(p1==1) return s1==1 && (s.charAt(0)==p.charAt(0) || p.charAt(0)=='.');
  6. //if(p1==1 && s1>1) return false;
  7. int i=0;
  8. int j=0;
  9. if(p.charAt(j+1) != '*') {
  10. if(i<s1 && (p.charAt(j) == s.charAt(i) || (p.charAt(j)=='.'))) {
  11. return isMatch(s.substring(i+1),p.substring(j+1));
  12. }
  13. else return false;
  14. }else {
  15. while(i<s1 && (p.charAt(j) == s.charAt(i) || (p.charAt(j)=='.'))) {
  16. if(isMatch(s.substring(i),p.substring(j+2))) {
  17. return true;
  18. }
  19. i++;
  20. }
  21. return isMatch(s.substring(i),p.substring(j+2));
  22. }
  23. // return false;
  24. }
posted @ 2014-08-10 21:54  purejade  阅读(78)  评论(0)    收藏  举报