http://oj.leetcode.com/problems/regular-expression-matching/ios
問題給想複雜了,只有p中能夠含有. *,s中的字符都是肯定的。想了很久,最終仍是參考了網上的答案。等我再想一想。express
#include <iostream> #include <map> #include <string> using namespace std; class Solution { public: bool isMatch(const char *s, const char *p) { if (s == NULL || p == NULL) return false; if (*p == '\0') return *s == '\0'; if (*(p + 1) == '*') { while ((*s != '\0' && *p == '.') || *s == *p) { if (isMatch(s, p + 2)) return true; //aab a*cd ++s; } return isMatch(s, p + 2); //aab c*ab 的狀況 } else if ((*s != '\0' && *p == '.') || *s == *p) { return isMatch(s + 1, p + 1); } return false; } }; int main() { Solution myS; char *s = "aab"; char *p = "a*cd"; myS.isMatch(s,p); return 0; }
因而,又試圖用本身的解法,來作這道題。spa
class Solution { public: bool isMatch(const char *s, const char *p) { if (s == NULL || p == NULL) return false; int j = 0,i = 0; char flagchar = '\0'; while(s[i]!='\0'&&p[j]!='\0') { if(s[i] == p[j] ) { flagchar = s[i]; i++; j++; } else if(p[j] == '.') { i++; j++; flagchar = '\0'; } else if(s[i]!= p[j] && p[j]!= '*' && p[j] != '\0' && p[j+1]!='\0' && p[j+1] == '*') { flagchar = p[j]; j+= 2; } else if(p[j]=='*') { if(flagchar == '\0') flagchar = s[i]; while(p[j+1]!='\0'&&p[j+1]==flagchar) j++; j++; while(s[i]!='\0'&&s[i]==flagchar) i++; } else break; } if(s[i]=='\0'&&p[j]=='\0') return true; return false; } };
可是在"aaa", "ab*a*c*a"裏,掛掉了。發現,當該邊的只是規模的時候,確實遞歸很是好用。在這個地方,確實得遞歸。code
在多種狀況匹配不肯定的時候,這個嘗試blog
while ((*s != '\0' && *p == '.') || *s == *p) { if (isMatch(s, p + 2)) return true; //aab a*cd ++s;
} return isMatch(s, p + 2); //aab c*ab 的狀況這裏,大讚啊!又長智商了。