1.本题知识点
字符串、递归
2. 题目描述
请实现一个函数用来匹配包括 . 和 * 的正则表达式。模式中的字符 . 表示任意一个字符,而 * 表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配。
3. 思路
这题对编程来说没多大难度,难点是理解题目和考虑全面,总体感觉有点绕。
首先要明白,字符串和模式串是每个字符依次比较的。而且要弄懂 . 和 * 的意思。
一、当模式串中的第二个字符不是“*”时(这种情况其实就是将字符依次比较就行了):
1、当前字符不相同: 直接返回false。
2、当前字符相同: 即不管是模式串和字符串相等,还是模式串为 . 时,都可以继续递归进入下一轮的匹配。
二、而当模式串中的第二个字符是“*”时:
1、当前字符不相同,跳过模式的当前字符和*,继续下一轮匹配。(这是*匹配0次的情况)如图,最终匹配成功:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/2152e9706062eb59abf97a72e7343f14.png)
2、当前字符相同, 又有两种情况:
① 模式后移2字符,相当于x*被忽略(这是*匹配0次的情况)。如图,最终匹配成功:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/16473b9bea45a595bf90a3bf8812f100.png)
② 模式串不变,字符串后移1位(这是*匹配多次的情况)。如图,最终匹配成功:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4e8049f04864609437ac7ae1027421f1.png)
Java版本:
package com.algorithm.str;
public class MatchPattern {
public static void main(String[] args) {
String str = "abbbaa";
String pattern = "ab*baa";
System.out.println(match(str.toCharArray(), pattern.toCharArray()));
}
static boolean match(char[] str, char[] pattern) {
if (str == null || pattern == null) {
return false;
}
int strIndex = 0;
int patternIndex = 0;
return matchCore(str, strIndex, pattern, patternIndex);
}
static boolean matchCore(char[] str, int strIndex, char[] pattern,int patternIndex) {
if (strIndex == str.length && patternIndex == pattern.length) {
return true;
}
if (strIndex != str.length && patternIndex == pattern.length) {
return false;
}
if (patternIndex + 1 < pattern.length && pattern[patternIndex + 1] == '*')
{
if ((strIndex != str.length && pattern[patternIndex] == str[strIndex])
|| (strIndex != str.length && pattern[patternIndex] == '.' ))
{
return matchCore(str, strIndex, pattern, patternIndex + 2)
|| matchCore(str, strIndex + 1, pattern, patternIndex);
}
else
{
return matchCore(str, strIndex, pattern, patternIndex + 2);
}
}
if (strIndex != str.length)
{
if(pattern[patternIndex] == str[strIndex] || pattern[patternIndex] == '.'){
return matchCore(str, strIndex + 1, pattern, patternIndex + 1);
}
}
return false;
}
}