'?' 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
Recursive solution. Cannot pass judge large.
public class Solution {
public boolean isMatch(String s, String p) {
// Start typing your Java solution below
// DO NOT write main() function
if (p.length() == 0) {
return s.length() == 0;
}
if (p.charAt(0) != '*') {
if (s.length() != 0
&& (p.charAt(0) == s.charAt(0) || p.charAt(0) == '?')) {
return isMatch(s.substring(1), p.substring(1));
} else {
return false;
}
}
// p.charAt(0) == '*'
while (s.length() != 0) {
while (p.length() > 1 && p.charAt(1) == '*') {
p = p.substring(1);
}
// p.charAt(1) != '*'
if (isMatch(s, p.substring(1))) {
return true;
}
s = s.substring(1);
}
return isMatch(s, p.substring(1));
}
}
Non_recursive solution
public class Solution {
public boolean isMatch(String s, String p) {
// Start typing your Java solution below
// DO NOT write main() function
if (p.length() == 0)
return s.length() == 0;
int i = 0; int j = 0;
int star = -1; int back = -1;
while (i < s.length()) {
if (j < p.length() && (p.charAt(j) == '?' || s.charAt(i) == p.charAt(j))) {
i++;
j++;
} else if (j < p.length() && p.charAt(j) == '*') {
back = i;
star = j;
j++;
} else {
if (star != -1) {
i = back + 1;
j = star + 1;
back = i;
} else {
return false;
}
}
}
while (j < p.length() && p.charAt(j) == '*')
j++;
return j == p.length();
}
}