題目描述:
請實現一個函數用來匹配包括’.’和’‘的正則表達式。模式中的字符’.’表示任意一個字符,而’‘表示它前面的字符可以出現任意次(包含0次)。 在本題中,匹配是指字符串的所有字符匹配整個模式。例如,字符串”aaa”與模式”a.a”和”ab*ac*a”匹配,但是與”aa.a”和”ab*a”均不匹配;
代碼如下:
public class Solution {
public 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);
}
private boolean matchCore(char[] str, int strIndex, char[] pattern, int patternIndex) {
// 若字符串和模式都已比對完成,且都匹配則返回true
if (strIndex == str.length && patternIndex == pattern.length) {
return true;
}
// 若字符串已遍歷完,而模式還沒有遍歷完,則返回false
if (strIndex != str.length && patternIndex == pattern.length) {
return false;
}
// 模式中第2個是 * ,且字符串第1個跟模式第1個匹配或模式的第一個爲 .,則有三種狀態
if (patternIndex + 1 < pattern.length && pattern[patternIndex + 1] == '*') {
if (strIndex != str.length && str[strIndex] == pattern[patternIndex] || (pattern[patternIndex] == '.' && strIndex != str.length)) {
// 模式匹配一個字符的情況,此時字符串後移1位,模式後移2位;如字符串爲ab,模式爲:a*b
return matchCore(str, strIndex + 1, pattern, patternIndex + 2)
// 模式匹配多個字符的情況,保持當前狀態,字符串後移1位;如字符串爲aab,模式爲:a*b
|| matchCore(str, strIndex + 1, pattern, patternIndex)
// 此時 X* 被忽略,模式加2;如字符串爲ab,模式爲:a*ab
|| matchCore(str, strIndex, pattern, patternIndex + 2);
} else {
return matchCore(str, strIndex, pattern, patternIndex + 2);
}
}
// 模式中第2個不是 * ,且字符串第1個跟模式第1個匹配,則都後移1位,否則直接返回false
if (strIndex != str.length && str[strIndex] == pattern[patternIndex] || (pattern[patternIndex] == '.' && strIndex != str.length)) {
return matchCore(str, strIndex + 1, pattern, patternIndex + 1);
}
return false;
}
}