LeetCode_OJ【44】Wildcard Matching

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

Subscribe to see which companies asked this question

本题给的提示是动态规划,回溯,贪心

一开始我只用回溯求解,写出如下算法:

public class Solution {
    public boolean isMatch(String s, String p) {
        if(p.length() == 0 || s.length() == 0)
        	return p.length() == 0 && s.length() == 0;
        else if(p.charAt(0) == '*'){
        	while(p.length() > 1 && p.charAt(1) == '*')
        		p = p.substring(1);
        	if(isMatch(s, p.substring(1)))
        		return true;
        	else
        		return isMatch(s.substring(1), p);
        }
        else if(p.charAt(0) == '?' || p.charAt(0) == s.charAt(0)){
        	return isMatch(s.substring(1), p.substring(1));
        }
        else 
        	return false;
	}
}

结果很多用例过不去。只用回溯的话,时间复杂度确实太高了,碰到稍长一点的字符串就需要很长的时间才跑出结果(我给没通过的例子在自己的机器上面跑了下,几分钟都没出结果)。

然后就想了下用动规应该怎么解,其实能写出回溯的算法基本就已经完成了一大半了。

这里使用一个二维数组记录s的子串和p的子串的匹配情况,res[0][0]表示s和p都匹配完了,所以为true;

res[o][j]表示p串匹配完了,s串还剩j个字符,res[i][0]表示s匹配完了,p还剩i个字符,初始化的时候可以得到这些数据。

后面可以根据回溯算法的求解过程依次求出res[i][j]。最后res[p.length()][s.length()]就是最终结果。

下面是该思路的JAVA实现。

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值