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
思路:
先是递归,不能过大集合;
循环可以过,但是p == '*'的情况需要特殊处理,用两个指针记录p == '*'时的s和p的位置。
因为p的*可以代表很多字符,需要确定*代表s中的那些字符
代码:
递归版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Solution { public : bool isMatch( const char *s, const char *p) { if (*p == '*' ) { while (*p == '*' ) p++; if (*p == '\0' ) return true ; while (*s != '\0' && !isMatch(s, p)) s++; return *s != '\0' ; } else if (*p == '\0' || *s == '\0' ) return *p == *s; else if (*p == '?' || *p == *s) return isMatch(++s, ++p); else return false ; } }; <br><br> |
循环版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | class Solution { public : bool isMatch( const char *s, const char *p) { if (!s && !p) return true ; const char *ss = NULL; const char *sp = NULL; while (*s) { if (*s == *p || *p == '?' ) { s++; p++; } else if (*p == '*' ) { while (*p == '*' ) p++; if (*p == '\0' ) return true ; ss = s; sp = p; } else if ((*p == '\0' || *p != *s) && sp) { s = ++ss; p = sp; } else return false ; } while (*p) if (*p++ != '*' ) return false ; return true ; } }; |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步