【剑指Offer】正则表达式匹配

题目

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

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public boolean match(char[] str, char[] pattern) {
if (str == null || pattern == null)
return false;

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

private boolean matchHelper(char[] str, int strIdx, char[] pattern, int patternIdx) {
if (strIdx == str.length && patternIdx == pattern.length)
return true;

if (strIdx != str.length && patternIdx == pattern.length)
return false;

if (patternIdx + 1 < pattern.length && pattern[patternIdx+1] == '*') {
if (strIdx < str.length && (str[strIdx] == pattern[patternIdx] || pattern[patternIdx] == '.'))
return matchHelper(str, strIdx, pattern, patternIdx + 2)
|| matchHelper(str , strIdx + 1, pattern, patternIdx)
|| matchHelper(str, strIdx + 1, pattern, patternIdx + 2);
else
return matchHelper(str, strIdx, pattern, patternIdx + 2);
}

if (strIdx < str.length && (str[strIdx] == pattern[patternIdx] || pattern[patternIdx] == '.'))
return matchHelper(str, strIdx + 1, pattern, patternIdx + 1);

return false;
}