LeetCode.10:Regular Expression Matching【DP】

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

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 = "a*"
Output: true
Explanation: '*' means zero or more of the precedeng 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

动态规划经典题目
思路:

  1. 定义状态转移数组dp[i][j]表示利用p的前j个字符与s的前i个字符的匹配结果(成功为true,失败为false)。初试状态下,全都为false。
  2. 考虑base case:
    1. s和p都为空,dp[0][0]=true
    2. s为空,p不为空,例如s="",p=“a*”,这时dp[0][i]取决于dp[0][i-2]
  3. 更新dp,两个for循环
    1. s[i] == p[j] || p[j] == ‘.’,那么dp[i][j] = dp[i-1][j-1],也就是既然s串的第i个字符能和p串的第j个字符匹配,那么s串的前i个和p串的前j个是否能匹配取决于s串的前i-1个字符和p串的前j-1个字符,能匹配则s串的前i个和p串的前j个则能匹配,反之不能。
    2. p[j] == ‘*’:
      1. s[i] != p[j-1] && p[j-1] != ‘.’,那么dp[i][j] = dp[i][j-2],也就是*号前面的那个字符在匹配的过程当中一个都不使用,即 a* 号代表空。这时dp[i][j]取决于 dp[i][j-2]
      2. else,即s[i] == p[j-1] 并且p[j] == '’ ,这样的话分三种情况,只要以下三种可以匹配,则dp[i][j]=true ,一是s的前i个和p的前j-2个(这时代表0个);二是s的前i个和p的前j-1个(这时代表1个);三是s的前i-1个和p的前j个(这时代表多个),代码表示为:dp[i][j] =dp[i][j-2] || dp[i][j-1] || dp[i-1][j]
        (这个比较难以理解,需要多想!)
package com.Ryan;

public class RegularExpressionMatching {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		RegularExpressionMatching regularExpressionMatching = new RegularExpressionMatching();
		String s = "ab";
		String p = ".*";
		System.out.println(regularExpressionMatching.isMatch(s, p));

	}

	public boolean isMatch(String s, String p) {
		boolean[][] dp = new boolean[s.length() + 1][p.length() + 1];
		dp[0][0] = true;
		for (int i = 1; i <= p.length(); i++) {
			if (p.charAt(i - 1) == '*') {
				dp[0][i] = dp[0][i - 2];
			}
		}
		for (int si = 1; si <= s.length(); si++) {
			for (int pi = 1; pi <= p.length(); pi++) {
				if (p.charAt(pi - 1) == '.' || p.charAt(pi - 1) == s.charAt(si - 1)) {
					dp[si][pi] = dp[si - 1][pi - 1];
				} else if (p.charAt(pi - 1) == '*') {
					if (p.charAt(pi - 2) != s.charAt(si - 1) && p.charAt(pi - 2) != '.') {
						dp[si][pi] = dp[si][pi - 2];
					} else {
						dp[si][pi] = (dp[si][pi - 2] || dp[si][pi - 1] || dp[si - 1][pi]);
					}
				}
			}
		}

		return dp[s.length()][p.length()];
	}

}

猜你喜欢

转载自blog.csdn.net/qq_32350719/article/details/89431285