《剑指offer》练习-面试题19-正则表达式的匹配

题目:请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配

链接:
https://www.nowcoder.com/practice/45327ae22b7b413ea21df13ee7d6429c?tpId=13&tqId=11205&tPage=3&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

思路:
当模式中的第二个字符不是“*”时

1、如果字符串第一个字符和模式中的第一个字符相匹配,那么字符串和模式都后移一个字符,然后匹配剩余的
2、如果字符串第一个字符和模式中的第一个字符不相匹配,直接返回false

当模式中的第二个字符是“*”时
如果字符串第一个字符跟模式第一个字符不匹配,则模式后移2个字符,继续匹配。如果字符串第一个字符跟模式第一个字符匹配,可以有3种匹配方式:
1、模式后移2个字符,相当于x*被忽略。例:ab与b*ab
2、字符串后移1字符,模式后移2字符。例:ab与a*b
3、字符串后移1字符,模式不变,继续匹配字符下一位,因为“*”可以匹配很多位。例:abbc与ab*c

package offer;

public class Solution19 {
	public boolean match(char[] str, char[] pattern) {
		if (str == null || pattern == null)
			return false;

		return matchCore(str, 0, pattern, 0);
	}

	public boolean matchCore(char[] str, int strIndex, char[] pattern, int patternIndex) {
		// str到尾并且pattern到尾,匹配成功
		if (strIndex == str.length && patternIndex == pattern.length) // 递归终止条件
			return true;
		// 只有pattern到尾而str没到尾,匹配失败
		if (strIndex != str.length && patternIndex == pattern.length)
			return false;

		// 模式第二个字符是*,且字符串1字符与模式1字符匹配,分3中匹配模式;如1字符不匹配,则模式后移2位
		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) // 模式后移2
						|| matchCore(str, strIndex + 1, pattern, patternIndex + 2) // 模式后移2,且1字符匹配
						|| matchCore(str, strIndex + 1, pattern, patternIndex); // 1字符匹配,模式位不变
			} else {
				return matchCore(str, strIndex, pattern, patternIndex + 2);
			}
		} else if ((strIndex != str.length && pattern[patternIndex] == str[strIndex]) // 模式2字符不是*,且字符串第1个跟模式1字符匹配,则后移1位;否则直接返回false
				|| ((strIndex != str.length) && pattern[patternIndex] == '.')) {// 也是递归终止条件哦
			return matchCore(str, strIndex + 1, pattern, patternIndex + 1);
		}
		return false;
	}

	// 这里的字符1、字符2并不局限于前两个字符,而是两个相连的字符里面的前后关系
	// 2字符的意思是当前字符的后面一个字符

}

你可能感兴趣的:(剑指offer刷题记录)