算法分析与设计课程(4):【leetcode】Wildcard Matching
来源:互联网 发布:意大利军事实力 知乎 编辑:程序博客网 时间:2024/04/29 15:51
Description:
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
算法分析:“*”把p分成若干部分,然后判断,这几部分是不是可以能在s中匹配到。先定义两个指针从s和p的头出发如果p的第一个部分可以和s的前面部分匹配,那么两个指针往右移同样长度到第二部分,直到找到最后。例如,如果s为“abba”,p为“a*a”。首先,我们判断*前面那部分是不是和s的前面部分匹配。’a‘和‘a‘可以匹配;那么判断p中第二个‘a‘在s中能否匹配。发现可以,所以 返回true。这个的时间复杂度是(O(n))。
代码如下:class Solution(object): def match(self, s, p, i, j, size): k = 0 while k < size: if s[k + i] != p[j + k] and p[j + k] != '?': return False k += 1 return True def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ if s == p or p == "*": return True size = len(p); d = [] if size == 0 or len(s) == 0: return False for i in range(size): if p[i] == '*': d.append(i) i = 0; j = 0; k = 0; ss = len(s) if len(d) == 0: if ss != size: return False return self.match(s, p, 0, 0, size) first = True while i < ss: if ss - i < size - j - len(d) + k: return False if self.match(s, p, i, j, d[k] - j): first = False if k == len(d) - 1: if d[k] == size - 1: return True tmp = size - 1 - d[k] return self.match(s, p, ss - tmp, d[k] + 1, tmp) i += d[k] - j; j = d[k] + 1; k += 1 if i == ss: while j < size: if p[j] != '*': return False j += 1 return True elif first: return False else: i += 1 return False运行结果:
0 0
- 算法分析与设计课程(4):【leetcode】Wildcard Matching
- 算法分析与设计课程(17):【leetcode】4Sum
- LeetCode算法题目: Wildcard Matching
- 算法分析与设计课程(3):【leetcode】Permutations
- 算法分析与设计课程(8):【leetcode】Sudoku Solver
- 算法分析与设计课程(9):【leetcode】Jump Game
- 算法分析与设计课程(10):【leetcode】Simplify Path
- 算法分析与设计课程(11):【leetcode】Gray Code
- 算法分析与设计课程(14):【leetcode】 Maximal Square
- 算法分析与设计课程(18):【leetcode】Clone Graph
- LeetCode(44) Wildcard Matching
- LeetCode OJ算法题(四十三):Wildcard Matching
- 算法学习之动态规划(leetcode 44 Wildcard Matching)
- 【leetcode 44】 Wildcard Matching 【正确算法】
- LeetCode算法题——Wildcard Matching
- 算法分析课每周练习 Wildcard Matching
- (算法分析Week9)Wildcard Matching[Hard]
- 算法设计与分析- Stable Matching-Gale_Shapley
- [P1339]热浪
- 论前任的正确打开方式
- LMS算法
- APPIUM测试学习
- 在o(1)时间删除链表节点
- 算法分析与设计课程(4):【leetcode】Wildcard Matching
- 欢迎使用CSDN-markdown编辑器
- BCB中的文件操作
- 北京楼市调控升级 二套房首付比例提至60%
- Controller使用注解@Value加载配置文件 --SpringMVC
- 项目经验之谈 —— 利用编译器及C语言特性<位域>进行内存边界检测
- pdo预处理
- mac下修改mySQL的密码
- 算法训练 关联矩阵