劍指offer面試題:正則表達式匹配

轉載自:http://www.cnblogs.com/AndyJee/p/4700373.html

題目:

請實現一個函數用來匹配包括'.'和'*'的正則表達式。模式中的字符'.'表示任意一個字符,而'*'表示它前面的字符可以出現任意次(包含0次)。 在本題中,匹配是指字符串的所有字符匹配整個模式。例如,字符串"aaa"與模式"a.a"和"ab*ac*a"匹配,但是與"aa.a"和"ab*a"均不匹配

思路:

假設字符串爲str,模式串爲pattern,考慮以下情況:

A. 模式串下一個字符爲*,即*(pattern+1)=='*':

如果當前字符匹配,即*str=*pattern或者*str='.' && *pattern!='\0',三種可能:

 1、模式串當前字符出現0次,即*表示當前字符出現0次,則str=str,pattern=pattern+2;

 2、模式串當前字符出現1次,即*表示當前字符出現1次,則str=str+1,pattern=pattern+2;

 3、模式串當前字符出現2次或2次以上,即*表示當前字符出現2次或以上,則str=str+1,pattern=pattern;

如果當前字符不匹配,則只能讓*表示當前字符出現0次,則str=str,pattern=pattern+2;

B. 模式串下一個字符不爲*

如果當前字符匹配,即*str=*pattern或者*str='.' && *pattern!='\0',則str=str+1,pattern=pattern+1.

代碼:

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

29

30

31

32

33

34

35

36

37

38

39

40

41

#include <iostream>

 

using namespace std;

 

bool RegMatchCore(const char* str, const char* pattern){

    if(*str=='\0' && *pattern=='\0')

        return true;

    if(*str!='\0' && *pattern=='\0')

        return false;

 

    if(*(pattern+1)=='*'){

        if(*str==*pattern || (*str!='\0' && *pattern=='.'))

            return RegMatchCore(str,pattern+2) || RegMatchCore(str+1,pattern+2) || RegMatchCore(str+1,pattern);

        else

            // ignore *

            return RegMatchCore(str,pattern+2);

    }

 

    if(*str==*pattern || (*str!='\0' && *pattern=='.'))

        return RegMatchCore(str+1,pattern+1);

 

    return false;

}

 

 

bool RegMatch(const char* str, const char* pattern){

    if(str==NULL || pattern==NULL)

        return false;

    return RegMatchCore(str,pattern);

}

 

 

int main()

{

    char str[] = "aaa";

    char pattern1[]="ab*ac*a";

    char pattern2[]="ab*a";

    cout << RegMatch(str,pattern1) << endl;

    cout << RegMatch(str,pattern2) << endl;

    return 0;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章