1. 程式人生 > >[正則表示式] hdu6170 two strings

[正則表示式] 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;
}