字符串匹配问题

1. 参考文章http://www.leetcode.com/2011/09/regular-expression-matching.html

2. 代码

View Code
 1 #include <iostream>
 2 #include <cassert>
 3 
 4 using namespace std;
 5 
 6 
 7 //递归很重要
 8 bool isMatch(const char* sor,const char* des)
 9 {
10     assert(sor && des);
11     //到达字符串末尾
12     if (*des=='\0')
13     {
14         return *sor=='\0';
15     }
16     //des当前字符的下一个字符不是‘*’
17     if (*(des+1)!='*')
18     {
19         assert(*des!='*');
20         //满足条件,则递归比较下一个字符
21         if ((*des==*sor) || ((*des=='.')&&(*sor!='\0')))
22         {
23             return isMatch(sor+1,des+1);
24         }
25     }
26     //如果下一个字符是'*',并且满足while条件
27     while ((*des==*sor) || (*des=='.' && *sor!='\0') )
28     {
29         if (isMatch(sor,des+2))
30         {
31             return true;
32         }
33         sor++;
34     }
35     //如果下一个字符是'*',并且不满足while条件
36     return isMatch(sor,des+2);
37 }
38 
39 int main()
40 {
41     cout<<isMatch("aa","a")<<endl;
42     cout<<isMatch("aa","aa")<<endl;
43     cout<<isMatch("aaa","aa")<<endl;
44     cout<<isMatch("aa","a*")<<endl;
45     cout<<isMatch("aa",".*")<<endl;
46     cout<<isMatch("ab",".*")<<endl;
47     cout<<isMatch("aab","c*a*b")<<endl;
48 }

3. 注意问题:

  (1)递归求解问题的重要性

  (2)深入了解题目的意思及要求

  (3)各种情况考虑清楚

  (4)学习题目中简洁的代码书写方式

posted @ 2012-07-21 10:23  kasuosuo  阅读(269)  评论(0编辑  收藏  举报