题目要求:Wildcard Matching
Implement wildcard pattern matching with support for ‘?‘
and ‘*‘
.
‘?‘ Matches any single character. ‘*‘ Matches any sequence of characters (including the empty sequence). 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", "*") → true isMatch("aa", "a*") → true isMatch("ab", "?*") → true isMatch("aab", "c*a*b") → false
参考网址:http://blog.csdn.net/pickless/article/details/9787227
代码如下:
class Solution { public: bool initCheck(const char *s, const char *p) { int l1 = 0; int idx = 0, l2 = 0; while (s[l1] != ‘\0‘) { l1++; } while (p[idx] != ‘\0‘) { l2 += p[idx++] != ‘*‘ ? 1 : 0; } return l1 >= l2; } bool isMatch(const char *s, const char *p) { // Start typing your C/C++ solution below // DO NOT write int main() function if (!initCheck(s, p)) { return false; } int l = 0; while (p[l++] != ‘\0‘); bool prev[l], f[l]; memset(f, false, sizeof(bool) * l); memset(prev, false, sizeof(bool) * l); bool isFirst = true; for (int i = 0; i < l; i++) { if (p[i] == ‘*‘) { f[i] = i == 0 || f[i - 1]; } else if ((p[i] == ‘?‘ || p[i] == *s) && isFirst) { isFirst = false; f[i] = true; } else { break; } } s++; while (*(s - 1) != ‘\0‘) { memcpy(prev, f, l); memset(f, false, sizeof(bool) * l); for (int i = 0; i < l; i++) { if (prev[i]) { f[i] = f[i] || p[i] == ‘*‘; f[i + 1] = f[i + 1] || p[i + 1] == ‘?‘ || p[i + 1] == *s; } else if (i == 0 || f[i - 1]) { f[i] = f[i] || p[i] == ‘*‘; } } s++; } return f[l - 1]; } };
时间: 2024-12-28 18:09:53