leetcode笔记:Wildcard Matching
来源:互联网 发布:网络安全工程师笔试题 编辑:程序博客网 时间:2024/06/11 18:24
一. 题目描述
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
二. 题目分析
题目的大意是,给出两串字符串s
和p
,规定符号?
能匹配任意单个字符,*
能匹配任意字符序列(包括空字符序列)。如果两串字符串完全匹配则返回true
。
该题的难点主要在于出现*
时的匹配操作。和网上大多数做法相似,一开始使用递归完成,结果总是超时。后来使用几个变量用于记录遇到p
中的*
时的下标,每次遇到一个*
,就保留住当前字符串s
和p
的下标,然后s从当前下标往后扫描,如果不匹配,则s的下标加一,重复扫描。
三. 示例代码
#include <iostream>#include <string>using namespace std;class Solution {public: bool isMatch(string s, string p) { int s_size = s.size(); int p_size = p.size(); int s_index = 0, p_index = 0; int temp_s_index = -1, temp_p_index = -1; while (s_index < s_size) { if (p[p_index] == '?' || p[p_index] == s[s_index]) { ++p_index; ++s_index; continue; } if (p[p_index] == '*') { temp_p_index = p_index; temp_s_index = s_index; ++p_index; continue; } if (temp_p_index >= 0) { // 字符串p可能有多个*,因此只要出现过*,则需要更新当前匹配的下标 p_index = temp_p_index + 1; s_index = temp_s_index + 1; // 当前坐标s与p不匹配,则s的坐标在原基础上加一,继续循环 ++temp_s_index; continue; } return false; } while (p[p_index] == '*') ++p_index; return p_index == p_size; }};
四. 小结
这种题目一般递归的思路还是首选,但递归的最大缺点就是耗时。该题若使用动态规划也可以解决,但是未必能达到以上方法的
3 0
- leetcode笔记:Wildcard Matching
- 【LeetCode笔记】Wildcard Matching 和 Regular Expression Matching
- LeetCode: Wildcard Matching
- LeetCode : Wildcard Matching
- [LeetCode] Wildcard Matching - Iteratively
- leetcode 83: Wildcard Matching
- [Leetcode] Wildcard Matching
- [LeetCode]Wildcard Matching
- LeetCode-Wildcard Matching
- LeetCode -- Wildcard Matching
- LeetCode | Wildcard Matching
- Leetcode: Wildcard Matching
- Leetcode:Wildcard Matching
- LeetCode题解:Wildcard Matching
- LeetCode Wildcard Matching
- [Leetcode] Wildcard Matching (Java)
- LeetCode OJ:Wildcard Matching
- Leetcode: Wildcard Matching
- iOS开发之Git的命令以及xocde打不开的原因
- Intel BayTrail gpio driver patch
- LInux 下安装 python notebook
- 对网络基本情况进行查看方法
- 推荐一款VPN(行云VPN)
- leetcode笔记:Wildcard Matching
- 解决Tomcat启动时项目重复加载问题
- Android 禁止ViewPager滑动
- ***Leetcode Median of Two Sorted Arrays
- 国内外三个不同领域巨头分享的Redis实战经验及使用场景
- Android事件分发机制之View篇
- 去除ViewPager的滑动事件(简单、暴力)
- 数据结构(1)-栈的特性以及简单应用
- Objective-C_语言_内存管理2(代码)