详细见:leetcode.com/problems/wildcard-matching
Java Solution: github
package leetcode;
public class P044_WildcardMatching {
/*
* 35 ms
* 54.88%
*/
static class Solution4 {
public boolean isMatch(String s, String p) {
if (p == null || p.length() == 0)
return s.length() == 0;
boolean[] res = new boolean[s.length() + 1];
res[0] = true;
for (int j = 0; j < p.length(); j++) {
if (p.charAt(j) != '*') {
for (int i = s.length() - 1; i >= 0; i--) {
res[i + 1] = res[i] && (p.charAt(j) == '?' || s.charAt(i) == p.charAt(j));
}
} else {
int i = 0;
while (i <= s.length() && !res[i])
i++;
for (; i <= s.length(); i++) {
res[i] = true;
}
}
res[0] = res[0] && p.charAt(j) == '*';
}
return res[s.length()];
}
}
}
C Solution: github
/*
url: leetcode.com/problems/wildcard-matching/
AC 56ms 9.01%
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define bool int
bool isMatch(char* s, char* p) {
int sn = s == NULL ? 0 : strlen(s);
int pn = p == NULL ? 0 : strlen(p);
char** m = (char**) malloc(sizeof(char*) * (sn + 2));
char* mt = NULL;
int si = 0, pi = 0;
//if (sn == 0 || pn == 0) return sn == 0 && pn == 0;
for (si = 0; si < sn + 2; si ++) {
*(m + si) = malloc(sizeof(char) * (pn + 2));
memset(*(m + si), '0', pn + 2);
}
m[0][0] = '1';
for (pi = 0; pi < pn; pi ++) {
if (m[0][pi] == '1' && p[pi] == '*')
m[0][pi + 1] = '1';
}
for (si = 0; si < sn; si ++) {
for (pi = 0; pi < pn; pi ++) {
if (p[pi] == '?' || p[pi] == s[si]) {
m[si + 1][pi + 1] = m[si][pi];
}
if (p[pi] == '*') {
if (m[si + 1][pi] == '1') {
m[si + 1][pi + 1] = '1';
continue;
}
if (m[si][pi] == '1') {
m[si + 1][pi + 1] = '1';
continue;
}
if (m[si][pi + 1] == '1') {
m[si + 1][pi + 1] = '1';
continue;
}
}
}
}
//ans
pi = m[sn][pn] - '0';
for (si = 0; si < sn + 2; si ++) {
free(*(m + si));
}
free(m);
return pi;
}
int main() {
char* s = "";
char* p = "*";
printf("answer is %d\r\n", isMatch(s, p));
return 0;
}
Python Solution: github
#coding=utf-8
'''
url: leetcode.com/problems/wildcard-matching
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年4月7日
@details: Solution: 1845ms 22.70%
'''
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
sn = 0 if s == None else len(s)
pn = 0 if p == None else len(p)
m = [[False for pi in range(pn+1)] for si in range(sn+1)]
m[0][0]=True
#m[0][0], si, pi = True, 0, 0
for pi in range(0, pn):
if p[pi]=='*' and m[0][pi]:
m[0][pi+1] = True
for si in range(0, sn):
for pi in range(0, pn):
if s[si]==p[pi] or p[pi]=='?':
m[si+1][pi+1]=m[si][pi]
elif p[pi]=='*':
if m[si][pi+1]: #match 0 time
m[si+1][pi+1]=True
continue
if m[si][pi]: #match 1 time
m[si+1][pi+1]=True
continue
if m[si+1][pi]: #match many times
m[si+1][pi+1]=True
continue
return m[sn][pn]
if __name__ == "__main__":
print(Solution().isMatch("", "*"))