LeetCode 10. Regular Expression Matching (动态规划) C++

Given an input string (s) and a pattern §, implement regular expression matching with support for ‘.’ and ‘*’.
给定输入字符串和模式(p),实现支持“ . ”和“ * ”的正则表达式匹配。

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

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可以是空的,并且只包含小写字母a-z。
  • p可以是空的,并且只包含小写字母a-z和字符 . 和 *。

Example 1:

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

Example 2:

Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".

Example 3:

Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".

Example 4:

Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches "aab".

Example 5:

Input:
s = "mississippi"
p = "mis*is*p*."
Output: false

分析:

用动态规划解决。其中dp[i][j]表示s[0......i-1]p[0......j-1]是否匹配,若匹配成功则返回true,不匹配则返回false
匹配的原则是2个字符串相等,即s[0.....i-1] == p[0......j-1],同时引入2个新字符.*,并且.*只会在字符串p中出现。其中:

.可以当作任意一个字符来使用。
*可以让他前面一位的字符使用0到无数次。(比如b*a 等价于 "", "ba" ,"baa", "baaa", "baaaa",······

另外可以发现d[i][j]里表示的字符,在字符串s或p中,下标需要减一,所以引入curP and curS方便算清楚下标。

难点在于某些特殊情况的处理,例如字符串abc*d

p=abc*d时,

s=abc,那么*d应该计算0次,即空串。dp[i][j] = dp[i][j-2]
s=abcd,那么*d应该计算1次。dp[i][j] = dp[i][j-1]
s=abcddd,那么*d应该计算3次。dp[i][j] = dp[i-1][j]
于是就需要把3种情况都试一遍,即dp[i][j] = dp[i][j-2]|| dp[i][j-1]|| dp[i-1][j];

C++代码

class Solution{
	public:
		bool isMatch(string s,string p){
			int m = s.size();
			int n = p.size();
			bool dp[m+1][n+1];
			memset(dp,0,sizeof(dp));//初始化为false
			dp[0][0] = true;//表示空串可以和空串匹配。
			for(int j=2;j<=n && p[j-1]=='*';j+=2){//表示若p = #*#*#*可以和空串(s="")匹配
				dp[0][j] = true;
			}
			//dp
			for(int i=1;i<=m;i++){
				for(int j=1;j<=n;j++){
					char curS = s[i-1];//声明curS 和curP 解决下标问题.
					char curP = p[j-1];
					if(curS == curP || curP == '.'){
						dp[i][j] = dp[i-1][j-1];
					}
					else if( curP == '*'){
						char precurP = p[j-2];// precurP 表示'?*'中的字符 "?";
						if(precurP != '.' && precurP!=curS){
							dp[i][j] = dp[i][j-2];//在这种情况下, *a 数零次
						}else{
							dp[i][j] = dp[i][j-2]|| //在这种情况下, *a 数零次
							           dp[i][j-1]|| //在这种情况下, *a 数一次
							           dp[i-1][j];  //在这种情况下, *a 数许多次
						}
					}
				}
			}
			return dp[m][n];
		}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值