Wildcard Matching -- leetcode
2015-01-21 11:49
295 查看
Implement wildcard pattern matching with support for
此算法在leetcode上实际执行时间为 27ms。
主要是对’*’的处理。
1.遇到’*’,首先偿试匹配0个。即不消耗当前s的字符。用p后续的匹配串,去对s进行匹配。
2.如果失败,则消耗掉当前s的字符。
此题用递归写的法,比较容易,但是在时间上很难被AC。原因在于递归时回溯的比较多。
此题想要在时间上被AC,要利用一个优化条件:
如果匹配失败,则只用回退最近上一个*处继续进行第2步处理。
参考:
https://oj.leetcode.com/discuss/10133/linear-runtime-and-constant-space-solution
'?'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
此算法在leetcode上实际执行时间为 27ms。
class Solution { public: bool isMatch(const char *s, const char *p) { const char *star = 0; const char *ss = 0; while (*s) { if (*p == *s || *p == '?') { ++p; ++s; } else if (*p == '*') { star = p++; ss = s; } else if (star) { p = star; s = ++ss; } else return false; } while (*p == '*') ++p; return !*p; } };
主要是对’*’的处理。
1.遇到’*’,首先偿试匹配0个。即不消耗当前s的字符。用p后续的匹配串,去对s进行匹配。
2.如果失败,则消耗掉当前s的字符。
此题用递归写的法,比较容易,但是在时间上很难被AC。原因在于递归时回溯的比较多。
此题想要在时间上被AC,要利用一个优化条件:
如果匹配失败,则只用回退最近上一个*处继续进行第2步处理。
参考:
https://oj.leetcode.com/discuss/10133/linear-runtime-and-constant-space-solution
相关文章推荐
- Leetcode44 Wildcard Matching
- [LeetCode]Wildcard Matching
- [Leetcode] Wildcard Matching
- leetcode Wildcard Matching ,Regular Expression Matching (正则表达式匹配和通配符匹配)
- LeetCode Wildcard Matching
- [LeetCode] Wildcard Matching, Solution
- [leetcode] Wildcard Matching 通配符匹配
- [Leetcode] 44. Wildcard Matching
- LeetCode: Wildcard Matching
- LeetCode_Wildcard Matching
- LeetCode 43 Wildcard Matching
- [LeetCode] Wildcard Matching 题解
- leetcode 44:Wildcard Matching
- [LeetCode]44. Wildcard Matching 深入浅出讲解和代码示例
- [LeetCode]Regular Expression Matching、Wildcard Matching
- leetcode:Wildcard Matching
- LeetCode-Wildcard Matching-通配符匹配-DP
- *LeetCode Wildcard Matching
- Leetcode 44. Wildcard Matching
- LeetCode | Wildcard Matching