[正则表达式] hdu6170 two strings

@(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() 的正则表达式。
    但此题有坑,.*的意义与正则表达式中不同,它代表的是同一字符的任意多个,而不是任意字符,也就是说,.*可以匹配aaaaabbbbb,但不能匹配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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值