通配符匹配

/*
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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值