给定一个输入字符串s 和模式p, p包含通配符?与星号’’, 其中输入s包含小写字母a-z, p包含小写字母a-z与?和星号, ?可以匹配任一字符, 星号*可以匹配多个字符,包括空字符。
给定输入s与p, 判断s 与 p是否完全匹配。
Example 1:
Input:
s = “aa”
p = “a”
Output: false
Explanation: “a” does not match the entire string “aa”.
Example 2:
Input:
s = “aa”
p = ""
Output: true
Explanation: '’ matches any sequence.
Example 3:
Input:
s = “cb”
p = “?a”
Output: false
Explanation: ‘?’ matches ‘c’, but the second letter is ‘a’, which does not match ‘b’.
Example 4:
Input:
s = “adceb”
p = “ab”
Output: true
Explanation: The first ‘’ matches the empty sequence, while the second '’ matches the substring “dce”.
Example 5:
Input:
s = “acdcb”
p = “a*c?b”
Output: false
分析:s.size() >= p.size()。所以最多匹配s.size()次。 依次匹配,当正确和p为问号时,继续匹配, 当p为星号时,暂停p的位移,直到s与p相同。当p匹配完毕时,检测p的指针位置是否为p的长度。
public bool isMatch(string s, string p) {
int i = 0, j = 0, iStar = -1, jStar = -1;
while (i < s.size()) {
if (s[i] == p[j] || p[j] == '?') {
++i; ++j;
} else if (p[j] == '') {
iStar = i;
jStar = j++;
} else if (iStar >= 0) {
i = ++iStar;
j = jStar + 1;
} else return false;
}
while (p[j] == '') ++j;
return j == p.size();
}