LeetCode 044.Wildcard Matching

Given an input string (s) and a pattern (p), 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).

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 *.

Example 1:

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

Example 2:

Input:
s = "aa"
p = "*"
Output: true
Explanation: '*' matches any sequence.

Example 3:

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

Example 4:

Input:
s = "adceb"
p = "*a*b"
Output: true
Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".

Example 5:

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

 

/*********************************************************/

又是一道我用naive方法做了很久,搞了半天,最后超时限。回过头来用动态规划做,一下就做完了的题目……

- 这道题动态规划的重点在于:用List[i][j]表示字符串s从0到i与字符串p从0到j进行匹配时的结果。当字符串p中j的位置是正确的字母或是?时,都非常简单,直接赋值List[i-1][j-1]即可。但如果p中j位置上是*,那么就变得复杂了。一种思路认为,当j位置上为*时

List[i][j] = List[i][j-1] || List[0][j-1] || List[1][j-1] || ........ || List[i-1][j-1]

因为当j位是*时,它可能不匹配,也可能匹配一个字符,也可能匹配n(0<=n<=i)个字符。

另一种思路则更简单——当j位置上为*时

List[i][j] = List[i][j-1] || List[i-1][j]

因为当*只要匹配一个以上的字符时,List[i][j] 的结果与 List[i-1][j] 一定是一样的。

有了思路代码就非常简单了,放上我自己的代码,语言是java

class Solution {
    public boolean isMatch(String s, String p) {
		int ls = s.length();
		int lp = p.length();
		boolean List[][] = new boolean[ls+1][lp+1];
		for(int k = 1;k<=ls;k++)
			List[k][0] = false;
		List[0][0] = true;
        for(int k = 0;k<lp && p.charAt(k) == '*' ;k++)
        {
            List[0][k+1] = true;
        }
		for(int j = 0; j<lp;j++)
		{
			for(int i = 0;i<ls;i++)
			{
				if(p.charAt(j)>='a' && p.charAt(j)<='z')
				{
					if(p.charAt(j) == s.charAt(i))
						List[i+1][j+1] = List[i][j];
					else List[i+1][j+1] = false;
				}
				else if(p.charAt(j)=='?')
				{
						List[i+1][j+1] = List[i][j];
				}
				else
				{
					List[i+1][j+1] = List[i][j+1] || List[i+1][j];
				}
			}
		}
		return List[ls][lp];
	}
    
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值