44. Wildcard Matching
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
解题思路:当碰到*的时候,需要记录下*的位置,之后如果不匹配的情况下,需要将pattern中的指针指向*号的下一个位置。然后在s中找到第一个与*的下一个位置相同的字母。
class Solution { public: bool isMatch(string s, string p) { if(p.empty())return s.empty(); int i=0,j=0; int starIndex=-1, match=0; while(i<s.length()){ if(s[i]==p[j]||p[j]=='?')i++,j++; else if(p[j]=='*'){ starIndex=j; match=i; j++; } else if(starIndex!=-1){ j=starIndex+1; match++; i=match; } else return false; } while(j<p.length()&&p[j]=='*')j++; return j==p.length(); } };