个人记录-LeetCode 44. Wildcard Matching
来源:互联网 发布:高中化学知识网络结构 编辑:程序博客网 时间:2024/06/02 09:52
问题:
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
这里唯一需要额外说明的是:问题要求的是完全匹配。
举例中的最后一项,“aab”仅为正则表达式“c*a*b”对应字符串的子串,因此结果还是false。
代码示例:
思路:
?号的处理比较简单,主要还是需要考虑如何处理*。
由于*可以替代0~任意多个字符,因此对应的匹配规则可以抽象成下图:
public class Solution { public boolean isMatch(String s, String p) { if (s == null || p ==null) { return false; } if (s.length() < 1) { return p.length() < 1 || p.equals("*"); } int sIndex = 0, pIndex = 0; boolean hasStar = false; //用于保存*后的第一个字符的位置 int afterStarIndexInP = -1; //用于保存与*匹配时,s中字符的位置 int starIndexInS = -1; while (sIndex < s.length()) { //完全相等时,s和p的下标同时增加 if (pIndex <= p.length() - 1 && (s.charAt(sIndex) == p.charAt(pIndex) || p.charAt(pIndex) == '?')) { ++sIndex; ++pIndex; continue; } //不相等,但碰到*号时 if (pIndex <= p.length() - 1 && p.charAt(pIndex) == '*') { hasStar = true; if (pIndex < p.length() - 1) { ++pIndex; } else { //*是最后正则字符串的最后一个位置,前面全部匹配了,那么结果一定就是成功的 return true; } //记录*后,第一个字符的位置 afterStarIndexInP = pIndex; //记录此时s中字符的位置,注意到sIndex并没有增加, //此时,就是假设*代表0个字符 starIndexInS = sIndex; continue; } //不匹配,但之前遇到过* if (hasStar) { //pIndex重新回到*后的第一个位置 pIndex = afterStarIndexInP; //增加startIndexInS的值 //即逐渐增加*代表的字符数量 sIndex = ++starIndexInS; continue; } //不匹配且无*,返回false return false; } //若正则表达式还有剩余长度,那么必须全为*,才是true //例如“abcd”和“abcd***”返回的true //但“abcd”和“abcd**e”返回的就是false while (pIndex < p.length()) { if (p.charAt(pIndex) != '*') { return false; } ++pIndex; } return true; }}
0 0
- 个人记录-LeetCode 44. Wildcard Matching
- LeetCode --- 44. Wildcard Matching
- [Leetcode] 44. Wildcard Matching
- Leetcode 44. Wildcard Matching
- leetcode 44. Wildcard Matching
- Leetcode 44. Wildcard Matching
- Leetcode:44. Wildcard Matching
- LeetCode 44. Wildcard Matching
- leetcode.44. Wildcard Matching
- LeetCode 44. Wildcard Matching
- Leetcode-44. Wildcard Matching
- [LeetCode] 44. Wildcard Matching
- [leetcode] 44. Wildcard Matching
- [LeetCode]--44. Wildcard Matching
- LeetCode 44. Wildcard Matching
- leetcode 44. Wildcard Matching
- LeetCode 44. Wildcard Matching
- 44. Wildcard Matching -- LeetCode
- Mutual Training for Wannafly Union #3
- Javascript高级程序设计——11.变量、作用域、缓存
- AsyncSocket写的客户端Socket,实现当服务器断开连接时弹窗提示
- 2016校招编程 lcs 动态规划
- 接收短信
- 个人记录-LeetCode 44. Wildcard Matching
- docker安装运行保存镜像容器
- Linux下的51单片机蜂鸣器实验
- 计算机大小端判别方法
- 《鸟哥linux私房菜》读书笔记
- NOI 2991:2011(思维/规律)
- Matlab图像处理——保存图像方法大全
- 数据结构实验之排序一:一趟快排
- 毕业设计展示项目六:WPF、C#船舶动力定位模拟系统