【LeetCode】10. Regular Expression Matching - Java实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaoguaihai/article/details/84058335

1. 题目描述:

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

2. 思路分析:

题目的意思是实现一种正则表达式的匹配。首先对于题意:

  • “a"对应"a”, 这种匹配不解释了;
  • 任意字母对应".", 这也是正则常见;
  • 0到多个相同字符x,对应"x*", 比起普通正则,这个地方多出来一个前缀x,x代表的是相同的字符中取一个,比如"aaaab"对应是"a*b";
  • "*“还有一个易于疏忽的地方就是它的"贪婪性"要有一个限度,比如"aaa"对应"a*a”,代码逻辑不能一路贪婪到底;

正则表达式如果期望着一个字符一个字符的匹配,是非常不现实的,而"匹配"这个问题,非常容易转换成"匹配了一部分",整个匹配不匹配,要看"剩下的匹配"情况,这就很好的把一个大的问题转换成了规模较小的问题:递归。

3. Java代码:

源代码见我GiHub主页

代码:

public static boolean isMatch(String s, String p) {
    if (p.length() == 0) {
        return s.length() == 0;
    }

    // 表示第一个字符是否匹配上
    boolean first_match = (s.length() != 0 && (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.'));

    // 如果pattern是"x*"类型的话,那么pattern每次要两个两个的减少。否则,就是一个一个的减少
    if (p.length() == 1 || p.charAt(1) != '*') {
        return first_match && isMatch(s.substring(1), p.substring(1));
    } else {
        return (isMatch(s, p.substring(2)) ||
                (first_match && isMatch(s.substring(1), p)));
    }
}

猜你喜欢

转载自blog.csdn.net/xiaoguaihai/article/details/84058335