/*
44. 通配符匹配
给你一个输入字符串 (s) 和一个字符模式 (p) ,请你实现一个支持 '?' 和 '*' 匹配规则的通配符匹配:
'?' 可以匹配任何单个字符。
'*' 可以匹配任意字符序列(包括空字符序列)。
判定匹配成功的充要条件是:字符模式必须能够 完全匹配 输入字符串(而不是部分匹配)。
示例 1:
输入:s = "aa", p = "a"
输出:false
解释:"a" 无法匹配 "aa" 整个字符串。
示例 2:
输入:s = "aa", p = "*"
输出:true
解释:'*' 可以匹配任意字符串。
示例 3:
输入:s = "cb", p = "?a"
输出:false
解释:'?' 可以匹配 'c', 但第二个 'a' 无法匹配 'b'。
提示:
0 <= s.length, p.length <= 2000
s 仅由小写英文字母组成
p 仅由小写英文字母、'?' 或 '*' 组成
https://leetcode.cn/problems/wildcard-matching/
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>
bool isMatch(char * s, char * p)
{
int len_s = strlen(s) + 1;
int len_p = strlen(p) + 1;
int i, j;
uint8_t *tmp = (uint8_t *)malloc(len_p * len_s * sizeof(uint8_t));
uint8_t (*dp)[len_s] = (uint8_t (*)[len_s])tmp;
memset(dp, 0, len_p * len_s * sizeof(uint8_t));
//for column 0 and row 0, set s/p as : 1 & 1, special char to match
dp[0][0] = 1;
for (i = 1; i < len_p; i++) {
if (p[i-1] == '*') {
dp[i][0] = dp[i-1][0];
}
}
for (i = 1; i < len_p; i++) {
bool matched_in_row = false;
for (j = 1; j < len_s; j++) {
if ((p[i-1] == s[j-1]) || (p[i-1] == '?')) {
//check [i-1][j-1] status, it decides matched or not
dp[i][j] = dp[i-1][j-1];
} else if (p[i-1] == '*') {
dp[i][j] = dp[i-1][j-1] || dp[i-1][j] || dp[i][j-1];
}
if (dp[i][j] && !matched_in_row) {
matched_in_row = true;
}
}
//check if a row not matched one, break, not need to compare
if (!matched_in_row) {
break;
}
}
bool ret = dp[len_p - 1][len_s - 1];
free(dp);
return ret;
}
int main(int argc, char *argv[])
{
if (argc != 3) {
printf("To check wildcard match, please input two string!\n");
return 0;
}
printf("is matched: %s\n", isMatch(argv[1], argv[2]) ? "true" : "false");
return 0;
}
通配符匹配
最新推荐文章于 2024-02-04 10:51:55 发布