题目
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
题意:给定两个字符串,一个是普通字符串,一个是用于匹配的字符串,匹配的字符串中的’?’能够代替任何一个字母,’*’能够代替任何长度的字符串。求解,两个字符串能否配对。
class Solution {
public:bool isMatch(const string& s, const string& p) {int si=0, pi=0;int slast, plast=-1;int slen=s.length(), plen=p.length();while (si < slen){if (s[si] == p[pi] || p[pi] == '?'){si++;pi++;}else if (pi < plen && p[pi] == '*') // 贪心{slast=si;while (pi < plen && p[pi] == '*'){pi++;}plast=pi;}else if (plast >= 0) // 有回溯位置,则回溯{si=slast+1;slast++;pi=plast;}else{return false;}}while (pi < plen && p[pi] == '*') pi++;return pi==plen;}
};
本文发布于:2024-02-01 21:15:05,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170679330739465.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |