【LeetCode】【JAVA】44. Wildcard Matching

44. Wildcard Matching

题目

Given an input string (s) and a pattern §, implement wildcard pattern matching with support for ‘?’ and ‘*’.

  • ‘?’ Matches any single character.
  • ‘*’ Matches any sequence ofcharacters (including the empty sequence).

The matching should cover the entire input string (not partial).
Note:

  • s could be empty and contains only lowercase letters a-z.
  • p could be empty and contains only lowercase letters a-z, and characters like ? or *.

给定一个字符串 (s) 和一个字符模式 § ,实现一个支持 ‘?’ 和 ‘*’ 的通配符匹配。

  • ‘?’ 可以匹配任何单个字符。
  • ‘*’ 可以匹配任意字符串(包括空字符串)。

两个字符串完全匹配才算匹配成功。
说明:

  • s 可能为空,且只包含从 a-z 的小写字母。
  • p 可能为空,且只包含从 a-z 的小写字母,以及字符 ? 和 *。

Example

Input:
s = “aa”
p = “a”
Output: false
Explanation: “a” does not match the entire string “aa”.

Input:
s = “aa”
p = ""
Output: true
Explanation: '
’ matches any sequence.

Input:
s = “cb”
p = “?a”
Output: false
Explanation: ‘?’ matches ‘c’, but the second letter is ‘a’, which does not match ‘b’.

Input:
s = “adceb”
p = “ab”
Output: true
Explanation: The first ‘’ matches the empty sequence, while the second '’ matches the substring “dce”.

Input:
s = “acdcb”
p = “a*c?b”
Output: false

解法

动态规划, dp[i][j]表示s的前i个字符和p的前j个字符是否匹配得上

代码

	public boolean isMatch(String s, String p) {
        boolean[][] dp = new boolean[s.length()+1][p.length()+1];
        
        dp[0][0] = true;
        for(int i = 0; i < p.length(); i++) {
        	
        	if(p.charAt(i) != '*')
        		break;
        	
        	dp[0][i+1] = dp[0][i];
        }
        
        for(int i = 1; i <= s.length(); i++) {
        	for(int j = 1; j <= p.length(); j++) {
        		if(s.charAt(i-1) == p.charAt(j-1) || p.charAt(j-1) == '?')
        			dp[i][j] = dp[i-1][j-1];
        		else if(p.charAt(j-1) == '*')
        			dp[i][j] = dp[i-1][j-1] || dp[i-1][j] || dp[i][j-1];
        	}
        }
        
        return dp[s.length()][p.length()];
    }

执行用时 : 56 ms, 在Wildcard Matching的Java提交中击败了79.93% 的用户
内存消耗 : 40.1 MB, 在Wildcard Matching的Java提交中击败了22.62% 的用户

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值