請實現一個函數用來匹配包括.和*的正則表達式。模式中的字符.表示任意一個字符,而*表示它前面的字符能夠出現任意次(包含0次)。 在本題中,匹配是指字符串的全部字符匹配整個模式。 例如,字符串aaa與模式a.a和ab*ac*a匹配,可是與aa.a和ab*a均不匹配。
"匹配"是指徹底匹配,即aaa與aaaa不匹配,只有aaa與aaa才能說是匹配。 b*能夠理解是''"也能夠是"bbbbbb*",例如ab*ac*a能夠理解爲"aaa",也能夠理解爲"abaa"或者"abaca"。
字符串:strA, 模式串patternB (1)patternB[j+1] != '*' 當strA[i] == patternB[j]或者patternB[j] == '.' and i < len(strA) 若是strA[i+1] != patternB[j+1], 返回False 若是strA[i+1] == patternB[j+1],進行下一輪比較 當strA[i] != patternB[j] and patternB[j] != '.' 直接返回Flase (2)patternB[j+1] == '*' 當strA[i] == patternB[j]或者patternB[j] == '.' and i < len(strA) 1)i不變,模式串 j = j + 2 2)j不變,字符串 i = i + 1 3)i = i+ 1, j = j + 2 當strA[i] != patternB[j] and patternB[j] != '.' 1)i不變,模式串 j = j + 2
def matchReg(strA: str, patternB: str, i: int = 0, j: int = 0) -> bool: if i == len(strA) and j == len(patternB): # 徹底匹配 return True if i < len(strA) and j == len(patternB) or (i == len(strA) and j < len(patternB)): return False if (j+1) < len(patternB) and patternB[j+1] == '*': if (patternB[j] == '.' and i < len(strA)) or (strA[i] == patternB[j]): return matchReg(strA, patternB, i, j + 2) or matchReg(strA, patternB, i + 1, j) or matchReg(strA, patternB, i + 1, j + 2) else: return matchReg(strA, patternB, i, j + 2) if (patternB[j] == '.' and i < len(strA)) or (strA[i] == patternB[j]): return matchReg(strA, patternB, i + 1, j + 1) return False