LeetCode 44 Wildcard Matching

本文介绍了一种实现通配符匹配的算法,支持 '?' 和 '*' 两种通配符,其中 '?' 匹配任意单个字符,'*' 匹配任意序列的字符。文章提供了两种解决方案:一种基于双指针的高效算法,另一种是基于动态规划的暴力求解方法,并给出了具体的代码实现及运行效率对比。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Implement wildcard pattern matching with support for '?' and '*'.

'?' 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

Runtime: 56 ms  beats 93.00% of java submissions.

	public boolean isMatch(String s, String p) {
		int i = 0, j = 0, match = 0, star = -1;		// i,j分别表示记录s与p的双指针
		while (i < s.length()) {
			if (j < p.length() && (p.charAt(j) == '?' || s.charAt(i) == p.charAt(j))) {  
				i++;
				j++;
			} else if (j < p.length() && p.charAt(j) == '*') { //这里'*'表示0个字符
				star = j; // 记录下此时'*'的位置信息,
				match = i;//此时对应的s的位置信息i
				j++;//继续往后
			} else if (star != -1) {  // 出现不匹配情况,回溯至'*'继续进行匹配  
				j = star + 1;   // 回溯到前面'*'处,继续进行匹配  
				i = ++match;  // 尝试s向前忽略一位,继续进行匹配  
			} else return false;// 完全不匹配情况
		}
		while (j < p.length() && p.charAt(j) == '*') j++;
		return j == p.length();
	}

参考http://blog.youkuaiyun.com/woliuyunyicai/article/details/49105557

以下是自己的brute force . Runtime: 123 ms  beats 27.31% of java submissions.

	public boolean isMatch(String ss, String pp) {
		if (pp.equals("*")) return true;
		int pn = pp.length(), sn = ss.length();
		boolean[][] dp = new boolean[sn + 1][pn + 1];
		char[] s = ss.toCharArray(), p = pp.toCharArray();
		dp[sn][pn] = true;
		for (int i = sn; i >= 0; i--)
			for (int j = pn - 1; j >= 0; j--)
				if (p[j] == '*')
					dp[i][j] = dp[i][j + 1] || i < sn && dp[i + 1][j];
				else dp[i][j] = i < sn && (p[j] == '?' || s[i] == p[j]) && dp[i + 1][j + 1];
		return dp[0][0];
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值