字符串匹配

2020-02-20 16:14:05

 

给定字符串str,其中绝对不含有字符’.’和’*’。再给定字符串exp,其中可以含有’.’或’*’,’*’字符不能是exp的首字符,并且任意两个’*’字符不相邻。exp中的’.’代表任何一个字符,exp中的’*’表示’*’的前一个字符可以有0个或者多个。请写一个函数,判断str是否能被exp匹配。
【举例】
str=“abc”,exp=“abc”。返回true。
str=“abc”,exp=“a.c”。exp中单个’.’可以代表任意字符,所以返回true。
str=“abcd”,exp=“.*”。exp中’*’的前一个字符是’.’,所以可表示任意数量的’.’字符,所以当exp是“....”时与“abcd”匹配,所以返回true。
str=“”,exp=“..*”。exp中’*’的前一个字符是’.’,可表示任意数量的’.’字符,但是”.*”之前还有一个’.’字符,该字符不受‘*’的影响,所以str起码得有一个字符才能被exp匹配。所以返回false。  
 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<string.h>
 4 using namespace std;
 5 int main()
 6 {
 7     char str[1000];
 8     char exp[1000];
 9     int i = 0;
10     int j = 0;
11     int count = 0;
12     cin>>str;
13     cin>>exp;
14     int tag = 0;
15     while ((i < strlen(str) - 1) && (j < strlen(exp) -1)) 
16     {
17         if (exp[j] == '.') 
18         {
19             count = 0;
20             i++;
21             j++;
22         }
23          else if (exp[j] == '*')
24         {
25             count++;
26             if (count >= 2) 
27             {
28                 tag = 0;
29                 break;
30             }
31             j++;
32         } 
33         else 
34         {
35             count = 0;
36             if (str[i] == exp[j]) 
37             {
38                 tag = 1;
39                 i++;
40                 j++;
41             } 
42             else 
43             {
44                 i++;
45             }
46         }
47     }
48     
49     
50     if (tag)
51     {
52         cout<<"YES"<<endl;
53         return 0;
54     }
55     cout<<"NO"<<endl;
56     return 0;
57 }
58 //懵懵懂懂中,不晓得有多适用 

 

 
posted @ 2020-02-20 16:38  龙龙666666  阅读(494)  评论(0编辑  收藏  举报