LeetCode Regular Expression Matching

本文详细介绍了如何实现正则表达式的匹配功能,支持'*'匹配零次或多次前一个元素,'.'匹配任意单字符。通过动态规划方法,实现了对于给定字符串和正则表达式的匹配判断。

Description:

Implement regular expression matching with support for '.' and '*'.

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

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", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true


Solution:

dp[i][j] represents whether s[0,i-1] and p[0,j-1] is a match.

We can have three situations s[i-1] and p[j-1]:

if p[j] != '.' and [j] != '*'
    dp[i][j] = dp[i-1][j-1] + s[i-1] == p[j-1];
else if p[j] == '.'
    dp[i][j] = dp[i-1][j-1];
else // p[j] = '*'
    if (j>1)
        if (dp[i][j-1] || dp[i][j-2])
            dp[i][j] = true
        else if(i>0 && dp[i-1][j] && (p[j-2]=='.' || s[i-1]==p[j-2] ) )  //(1)
            dp[i][j] = true

(1) Because we may have the situation that "" and ".*" is a match, so we need to start i from 0.


<span style="font-size:18px;">public class Solution {
	public boolean isMatch(String s, String p) {
		if (s == null || p == null)
			return false;

		int n = s.length();
		int m = p.length();

		boolean dp[][] = new boolean[n + 1][m + 1];
		dp[0][0] = true;

		char ch1, ch2;
		for (int i = 0; i <= n; i++) {
			for (int j = 1; j <= m; j++) {
				ch2 = p.charAt(j - 1);

				if (ch2 == '*') {
					if (j > 1) {
						if (dp[i][j - 1] || dp[i][j - 2])
							dp[i][j] = true;
						else if (i > 0
								&& (p.charAt(j - 2) == s.charAt(i - 1) || p
										.charAt(j - 2) == '.') && dp[i - 1][j])
							dp[i][j] = true;
					}
				} else if (i > 0) {
					ch1 = s.charAt(i - 1);
					if (ch2 == '.') {
						dp[i][j] = dp[i - 1][j - 1];
					} else {
						if (ch1 == ch2)
							dp[i][j] = dp[i - 1][j - 1];
					}
				}
			}
		}
		return dp[n][m];
	}
}</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值