LintCode 192:Wildcard Matching

Description:
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:
采用动态规划。开启(M+1)*(N+1)的数组空间。dp[0][i],dp[i][0]为其中一个字符串不包含任何字符的情况。
p[i-1]=='*'(注意字符串的index和dp中的index差1),找到一个最小j使得dp[i-1][j]为true,设置dp[i][j~N]均为true。
p[i-1]!='*',若dp[i-1][j-1]为true且p[i-1]=='?'或p[i-1]==s[j-1]的情况下,设置dp[i][j]=true。
最终dp[M][N]即为两个字符串是否match的结果。


Code:

class Solution {
public:
	/**
	* @param s: A string
	* @param p: A string includes "?" and "*"
	* @return: A boolean
	*/
	bool isMatch(string &s, string &p) {
		// write your code here
		int sl = s.size();
		int pl = p.size();
		bool** dp = new bool*[pl + 1];
		for (int i = 0; i<pl + 1; i++) {
			dp[i] = new bool[sl + 1];
			for (int j = 0; j < sl + 1; j++)
				dp[i][j] = 0;
		}
		int j;
		dp[0][0] = 1;
		for (int i = 1; i<pl + 1; i++) {
			if (p[i - 1] == '*') {
				j = 0;
				while (!dp[i - 1][j] && j<sl + 1) {
					j++;
				}
				for (int k = j; k<sl + 1; k++)
					dp[i][k] = 1;
			}
			else {
				for (int k = 1; k<sl + 1; k++) {
					if (dp[i - 1][k - 1]) {
						if (p[i - 1] == '?' || p[i - 1] == s[k - 1])
							dp[i][k] = 1;
					}
				}
			}
		}
		bool result = dp[pl][sl];
		for (int i = 0; i<pl + 1; i++)
			delete[] dp[i];
		delete[] dp;
		return result;
	}
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值