题目描述
请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配
解题思路:
首先,分别定义两个数组的下标变量index1和index2,分别代表字符串数组和模式串数组的下标。
分为以下几种情况:
1.如果字符串和模式串的下标都指向了最后,说明字符串和模式串完全匹配,返回true;
2.字符串和模式串的匹配过程中,如果模式串的下标已经到了最后,但是字符串的下标还没有,说明不匹配,返回false;
3.当模式串中的第二个字符是*的时候,又分以下几种情况:
(1)字符串和模式串的第一个字符匹配:
a.*取0,则模式串后移两位;
b.*取1,模式串后移两位,字符串后移一位;
c.*取大于2,字符串后移一位。
(2)如果字符串和模式串的第一个字符不匹配,则模式串后移两个字符,继续匹配。
4.当模式串中的第二个字符不是*的时候:
(1)如果字符串的第一个字符和模式串的第一个字符匹配,则字符串和模式串都后移一位继续匹配;
(2)如果字符串的第一个字符和模式串的第一个字符不匹配,则直接返回false。
public class Solution {
public boolean match(char[] str, char[] pattern) {
if (str == null || pattern == null) {
return false;
}
int index1 = 0;
int index2 = 0;
return match(str, index1, pattern, index2);
}
public static boolean match(char[] str, int index1, char[] pattern, int index2) {
if (index1 == str.length && index2 == pattern.length ) {
return true;
}
if (index1 != str.length && index2 == pattern.length ) {
return false;
}
if (index2 + 1 < pattern.length && pattern[index2 + 1] == '*') {
if (( index1 != str.length && str[index1] == pattern[index2]) || (index1 != str.length && pattern[index2] == '.')) {
return match(str, index1, pattern, index2 + 2) || match(str, index1 + 1, pattern, index2 + 2) || match(str, index1 + 1, pattern, index2);
} else {
return match(str, index1, pattern, index2 + 2);
}
}
if (index1 != str.length && str[index1] == pattern[index2] || pattern[index2] == '.') {
return match(str, index1 + 1, pattern, index2 + 1);
} else {
return false;
}
}
}