Leetcode_10_RegularExpressionMatching正则表达式匹配与Leetcode_44_WildcardMatching模糊匹配

 

一、 Leetcode_10_RegularExpressionMatching正则表达式匹配

1. 题目介绍:

*Leetcode_10_RegularExpressionMatching_Hard
* https://leetcode.com/problems/regular-expression-matching/
* Given an input string (s) and a pattern (p), implement regular expression
* matching with support for '.' and '*'.
* (1)、'.' Matches any single character.
* (2)、'*' 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 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

2. 思路分析

* 正则表达式匹配与模糊匹配的区别:
* 模糊匹配中,'?'表示单个任意字符;等同于正则中的'.';
* 但是模糊匹配中的'*'可以表示任意个任意字符;
* 而正则中'*'表示前面字符可以出现任意多个,如0个、1个或多个。
* 这样的话,模糊匹配中,'*'可以单独去匹配字符串;
* 但是正则中,'*'必须依赖于前面的字符,如"a*"或".*"去匹配。
* 正则匹配:
* 也是分成两种情况:
* ①当ps[i]!='*'时,与模糊匹配一样:与左上角值有关;
* dp[i][j] = dp[i - 1][j - 1] && (ps[i - 1] == '.' || ps[i - 1] == ss[j - 1])
* ②当ps[i]=='*'时,两种情况:
* A. *代表0,说明前一个元素ps[i-1]可以一个字符不匹配,即dp[i][j]=i > 1 && dp[i - 2][j];
* B. *代表大于1,匹配多个,此时在匹配一个的基础上(dp[i][j - 1]==true),
* 前一个字符ps[i-2]为'.'或前一个元素与ss[j-1]相等。(i-2是因为i是从1开始的到lp结束的)。

3. JAVA代码

public boolean isMatch(String s, String p) {
        if (s != null && s.equals(p)) return true;
        char[] ss = s.toCharArray(), ps = p.toCharArray();
        int ls = ss.length, lp = ps.length;
        //创建dp数组并初始化
        boolean[][] dp = new boolean[lp + 1][ls + 1];
        dp[0][0] = tr
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值