LeetCode Wildcard Matching

来源:互联网 发布:c语言If else例题 编辑:程序博客网 时间:2024/06/14 09:41

题目:

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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "*") → trueisMatch("aa", "a*") → trueisMatch("ab", "?*") → trueisMatch("aab", "c*a*b") → false
class Solution {public:bool isMatch(const char *s, const char *p) {if (!*s && !*p)return true;else if (*p == *s || (*p == '?' && *s))return isMatch(s + 1, p + 1);else if (*p == '*') {bool res = false;//连续多个*与单个*效果相同while (*p == '*')     p++;//若*后面没有字符,则匹配if (!*p) return true;while (*s) {const char *ts = s, *tp = p;while (*ts && (*ts == *tp || *tp == '?')) {ts++, tp++;if (*tp == '*')break;}if (!*ts && !*tp)return true;if (*tp == '*')return isMatch(ts, tp);if (!*ts) return false;s++;}return false;}elsereturn false;}};


0 0
原创粉丝点击