剑指offer52:正则表达式匹配

1 题目描述

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

2 思路和方法

  正则表达式中有三种情况:
  a.普通字符
  b.字符’.’
  c.普通字符或’.’ + 字符’*’

  碰到情况a、b都直接对比可以匹配,
  难点在于处理情况c
  情况c可以分两种子情况处理:
  c1.字符串的首字母与模式的首字母不匹配,模式直接右移两格(相当于’*’前面的字符出现了0次)
  c2.字符串的首字母与模式的首字母匹配,则:
    字符串右移一格,模式不移动(’*’前面的字符出现了不止一次)
    或字符串右移一格,模式右移两格(’*’前面的字符出现了刚好一次)
    或字符串不移动,模式右移两格(’*’前面的字符出现了0次)

  当字符串和模式同时走到结尾+1的位置,则表示匹配
  当字符串走到结尾+1的位置,模式还没走到结尾+1的位置,还要继续匹配(因为模式后面可能还有a*b*可以匹配0个字符串)
  当字符串还没走到结尾+1的位置,模式走到结尾+1的位置,则表示不匹配

3 C++核心代码

 1 class Solution {
 2 public:
 3     bool match(char* str, char* pattern) {
 4         if(str == nullptr && pattern == nullptr)
 5             return true;
 6         return matchCore(str, pattern);
 7     }
 8     bool matchCore(char* str, char* pattern){
 9         if(*str == '\0' && *pattern == '\0')    //
10             return true;
11         if(*str != '\0' && *pattern == '\0')    //
12             return false;
13         if(*(pattern+1) == '*'){
14             // 当前字符匹配
15             if( *pattern == *str || (*pattern == '.' && *str!='\0')){
16                 return matchCore(str+1, pattern)      //str字符串右移一格,(’*’前面的字符出现了不止一次)模式不移动
17                     || matchCore(str+1, pattern+2)    //str或字符串右移一格,模式右移两格(’*’前面的字符出现了刚好一次),模式状态改变
18                     || matchCore(str, pattern+2);     //str或字符串不移动,模式右移两格(’*’前面的字符出现了0次)忽略*字符
19             }
20             else
21                 return matchCore(str, pattern+2);    // 当前字符不匹配 忽略 *
22         }
23         // 逐个字符匹配
24         if(*str == *pattern || (*pattern == '.' && *str!='\0'))
25             return match(str+1,pattern+1);
26         return false;
27     }
28 };
View Code

参考资料

https://blog.csdn.net/zjwreal/article/details/89055244(代码)

https://blog.csdn.net/u013908099/article/details/85954619(思路)

https://blog.csdn.net/qq1263292336/article/details/75734596(思路)

posted @ 2019-08-29 12:02  wxwreal  阅读(133)  评论(0编辑  收藏  举报