- /*
- 题目:
- 实现一个函数用来匹配包含'.'和'*'的正则表达式.
- '.'表示比配任意字符,'*'表示匹配 0 个或多个字符串.
- */
- /*
- 思路:
- 采用递归的方法.
- 基础条件: 当字符串和模式串存在空的情况.
- 其它情况: 考虑模式为'**'的情况和不为'**'的情况.
- */
- #include<iostream>
- #include<string.h>
- #include<algorithm>
- #include<cmath>
- #include<stdio.h>
- using namespace std;
- bool coreMatch(char* str,char* pattern){
- //str 或 pattern 有空的情况下
- if(*str == '\0' && *pattern == '\0'){
- return true;
- }
- if(*str != '\0' && *pattern == '\0'){
- return false;
- }
- if(*str == '\0' && *pattern != '\0'){
- if(*(pattern+1) == '*' ){
- return coreMatch(str,pattern+2);
- }
- return false;
- }
- //str 和 pattern 均不空
- if(*(pattern+1) == '*'){
- if(*pattern != *str && *pattern != '.'){
- bool flag = coreMatch(str,pattern+2);
- return flag;
- }else{
- bool flag = (coreMatch(str,pattern+2) || coreMatch(str+1,pattern) || coreMatch(str+1,pattern+2));
- return flag;
- }
- }else if(*str == *pattern || *pattern == '.' ){
- return coreMatch(str+1,pattern+1);
- }
- return false;
- }
- bool match(char* str, char* pattern)
- {
- if(str == nullptr || pattern == nullptr){
- return false;
- }
- return coreMatch(str,pattern);
- }
- int main(){
- cout<<coreMatch("",".*");
- }
来源: http://www.bubuko.com/infodetail-3295377.html