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
static class Solution1 {
/**
* time running: O(n)
* bbarc
* *c
* @param s
* @param p
* @return
*/
public boolean isMatch(String s, String p) {
if (s == null && p == null) return true;
if (s == null || p == null) return false;
int sp = 0, pp = 0, star = -1, match = 0;
while (sp < s.length()) {
if (pp < p.length() && (s.charAt(sp) == p.charAt(pp) || p.charAt(pp) == '?')) {
sp++;
pp++;
} else if (pp < p.length() && p.charAt(pp) == '*') {
star = pp;
match = sp;
pp++;
} else if (star != -1) {
pp = star + 1;
match++;
sp = match;
} else {
return false;
}
}
while (pp < p.length() && p.charAt(pp) == '*') pp++;
return pp == p.length();
}
}
题目2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
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", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true