LeetCode 44. Wildcard Matching解题思路

题目意思为s为源字符串,p为带有通配符的匹配字符串,其中?带表一个字符,而*可代表空或是任一子串,?比较好处理,但是*可代表空或是任一子串,因此不好从头到尾一个字节一个字节比较,这里考虑采用动态规划的方式来处理。分为以下几种情况处理:

1. s为#####a, p为#####a,那么直接将s和p中的最后一个字符去掉,s[0:i-1]和p[0:j-1]

2. s为#####a, p为#####?, 情况同1

3. s为#####a, p为#####*, 由于*可代表0个字符,那么可比较s和p[0:j-1]; *可代表任一字符,那么比较s[0:j-1]和p即可

4. 两个字符串不匹配

所以得到递推式如下:

1. match[i][j] = match[i-1][j-1]       如果p[j-1]为?或p[j-1]==s[i-1]

2. match[i][j] = match[i][j-1]   ||    match[i-1][j]     如果p[j-1]为*

3. match[i][j] = false   其它情况

初始条件:match[0][0]两个字串为空,结果为true,注意矩阵中靠边的值的计算,不要出现index out of range就好了,golang实现代码如下:

func isMatch(s string, p string) bool {
	matchArray := make([][]bool, len(s)+1)

	for i := 0; i < len(s)+1; i++ {
		matchArray[i] = make([]bool, len(p)+1)
		for j := 0; j < len(p)+1; j++ {
			matchArray[i][j] = false
		}
	}

	matchArray[0][0] = true
	for j := 1; j < len(p)+1; j++ {
		if p[j-1] == '*' {
			matchArray[0][j] = matchArray[0][j-1]
		} else {
			matchArray[0][j] = false
		}
	}

	for i := 1; i < len(s)+1; i++ {
		if s[i-1] == '*' {
			matchArray[i][0] = matchArray[i-1][0]
		} else {
			matchArray[i][0] = false
		}
	}

	for i := 1; i < len(s)+1; i++ {
		for j := 1; j < len(p)+1; j++ {
			if s[i-1] == p[j-1] || p[j-1] == '?' {
				matchArray[i][j] = matchArray[i-1][j-1]
			} else if p[j-1] == '*' {
				matchArray[i][j] = matchArray[i-1][j] || matchArray[i][j-1]
			} else {
				matchArray[i][j] = false
			}
		}
	}

	return matchArray[len(s)][len(p)]
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值