1. 程式人生 > >HDU 6170 Two strings (dp)

HDU 6170 Two strings (dp)

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

題意

給出原串與匹配串,問能否匹配原串中所有的字元。

思路

如果這是一個標準的正則匹配,是不是可以直接用語言特性了呢?

我們設原串為 a ,匹配串為 bdp[i][j] 代表 b[1..i]a[1..j] 是否匹配成功。

顯然 dp[0][0] = true

對於其他情況:

  • 如果 b[i] == '.' ,則此時 a[j] 可以是任意字元, dp[i][j]dp[i-1][j-1] 轉移而來。

  • 如果 a[j] == b[i] ,同樣 dp[i][j]dp[i-1][j-1] 轉移而來。

  • 如果 b[i] == '*' ,假設該 * 最終可以匹配 0 位,則 dp[i][j] 狀態從 dp[i-2][j] 轉移而來,假設最終匹配 1 位,則從 dp[i-1][j] 轉移而來;

    假如 a[1..j-1]b[1..i-1] 已成功匹配,並且 a[j-1] == a[j] ,顯然當前的 * 可以繼續匹配這一個字元,因此 dp[i][j] = true

    假如 a[1..j-1]b[1..i] 已成功匹配(當前 * 已成功匹配若干位),且 a[j-1] == a[j] ,則可以繼續匹配這一個字元,因此 dp[i][j] = true

  • 特別的,如果 b[i] == '*' ,則 dp[i][0] 可以從 dp[i-2][0] 轉移而來,因此 dp[i][0] |= dp[i-2][0]

AC 程式碼

#include <bits/stdc++.h>
using namespace std;
const int maxn=2600;

char a[maxn],b[maxn];
bool dp[maxn][maxn];
int lena,lenb;
int main()
{
    int T;
    scanf("%d%*c",&T);
    while(T--)
    {
        memset(dp,false,sizeof(dp));
        a[0]=b[0]=1;
        gets(a+1);
        gets(b+1);
        lena = strlen(a) - 1;
        lenb = strlen(b) - 1;
        dp[0][0]=true;
        for(int i=1; i<=lenb; i++)
        {
            if(i>=2&&b[i]=='*')
                dp[i][0] |= dp[i-2][0];
            for(int j=1; j<=lena; j++)
            {
                if(b[i]=='.'||a[j]==b[i])
                    dp[i][j]=dp[i-1][j-1];
                else if(b[i]=='*')
                {
                    dp[i][j]=dp[i-2][j]|dp[i-1][j];
                    if((dp[i-1][j-1]||dp[i][j-1])&&a[j-1]==a[j])
                        dp[i][j] = true;
                }
            }
        }
        puts(dp[lenb][lena]?"yes":"no");
    }
    return 0;
}