LeetCode 44 Wildcard Matching (C++, Python)
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
Solution C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | class Solution { public: bool isMatch(string s, string p) { int index = 0; for (int i = 1; i < p.length(); ++ i) { if ((p[i] == '*') && (p[i] == p[i - 1])) continue; p[++index] = p[i]; } if (index + 1 < p.length()) p.resize(index + 1); // index to star in pattern p int starp = -1; // index s when the corresponding char in pattern p is star int stars = -1; // current pointers to p and s int ip = 0; int is = 0; while (is < s.length()) { if (ip != p.length() && p[ip] == '*') { starp = ip ++; stars = is; continue; } if (ip != p.length() && (p[ip] == s[is] || p[ip] == '?')) { ++ ip; ++ is; continue; } // not match if (starp != -1) { ip = starp + 1; is = ++ stars; continue; } return false; } while (ip < p.length() && p[ip] == '*') { ++ ip; } return ip == p.length(); } }; |
Solution Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | class Solution: # @param {string} s # @param {string} p # @return {boolean} def isMatch(self, s, p): starp = -1 stars = -1 inp = 0 ins = 0 while ins < len(s): if inp != len(p): if p[inp] == '*': starp = inp stars = ins inp += 1 continue if p[inp] == s[ins] or p[inp] == '?': inp += 1 ins += 1 continue if starp != -1: inp = starp + 1 stars += 1 ins = stars continue return False while inp < len(p) and p[inp] == '*': inp += 1 return inp == len(p) |