@(ACM题目)[字符串,正则表达式]
Description
Giving two strings and you should judge if they are matched.
The first string contains lowercase letters and uppercase letters.
The second string contains lowercase letters, uppercase letters, and special symbols: “.” and “*”.
. can match any letter, and * means the front character can appear any times. For example, “a.b” can match “acb” or “abb”, “a*” can match “a”, “aa” and even empty string. ( “” will not appear in the front of the string, and there will not be two consecutive “”.
Input
The first line contains an integer T implying the number of test cases. (T≤15)
For each test case, there are two lines implying the two strings (The length of the two strings is less than 2500).
Output
For each test case, print “yes” if the two strings are matched, otherwise print “no”.
Sample Input
3
aa
a*
abb
a.*
abb
aab
Sample Output
yes
yes
no
题目分析
.
可以匹配任意一个字符,*
可以匹配前面那个字符任意多次,求一个表达式能否匹配一个字符串。
此题有dp解法,这里使用运行比较慢、但也是 O(能过) 的正则表达式。
但此题有坑,.*
的意义与正则表达式中不同,它代表的是同一字符的任意多个,而不是任意字符,也就是说,.*
可以匹配aaaaa
或bbbbb
,但不能匹配ab
。
所以需要替换.*
为(.)\n*
,其中:
- 小括号为一个group,group可以对一个字符串应用规则,而不是限制在单个字符
\n
为backreferences ,其中n为正整数,代表与第n个group中的内容完全相同,关于backreference请参阅这里- *的含义同题意
最后再注意一下按行读入的问题。
代码
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 3000;
string s1, s2, s3;
int main()
{
ios::sync_with_stdio(false);
int T;
cin >> T;
cin.get();
for(int tt = 0; tt < T; ++tt)
{
getline(cin, s1);
getline(cin, s2);
int num = 0;
s3 = "";
for(int i = 0; i < s2.size(); ++i)
{
if(s2[i] == '.' && i+1 < s2.size() && s2[i+1] == '*') continue;
if(s2[i] == '*' && s2[i-1] == '.') s3.append("(.)\\" + (string){++num + '0'} + "*");
else s3.append((string){s2[i]});
}
if(regex_match(s1, regex(s3))) cout << "yes" << endl;
else cout << "no" << endl;
}
return 0;
}