'?' 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
我原来的想法,是通过一个二维数组,boolean matrix[i][j] 表示p中前i个元素与s中前j个元素的匹配情况
无奈,TLE
===
//摘自DISCUSS中的方法 :
public class Solution {
public boolean isMatch(String s, String p) {
int m = s.length(), n = p.length();
int count = 0;
// 计算p中'*'的个数
for (int i = 0; i < n; i++) {
if (p.charAt(i) == '*') count++;
}
if (count==0 && m != n) return false;
else if (n - count > m) return false;
// 这个数组表示的是字符串s中,前i个元素的匹配情况
boolean[] match = new boolean[m+1];
match[0] = true;
for (int i = 0; i < m; i++) {
match[i+1] = false;
}
// 他这种方法,原本应当用一个二维矩阵来存值的,但是实际上我们用到的只有它的上一层,所以,这里只用
// 一个一维的数组来存值即可
for (int i = 0; i < n; i++) { // row
if (p.charAt(i) == '*') {
for (int j = 0; j < m; j++) { // col
// 如果s中前j个个都匹配,那么自然*与第j+1个元素匹配,如果j+1元素都匹配,那么'*'就匹配空字符
match[j+1] = match[j] || match[j+1];
}
} else {
//对于!= '*'的元素 为什么要从后往前了, 因为考虑到前面的可能可能被之前的元素匹配了啊!!
for (int j = m-1; j >= 0; j--) { // 从后往前
// match[j]代表的是前j个元素是否已经匹配,如果false,那么这里匹配也没用
match[j+1] = (p.charAt(i) == '?' || p.charAt(i) == s.charAt(j)) && match[j];
}
match[0] = false;
}
}
return match[m];
}
}