1. 程式人生 > >hdu6170Two strings(第九場遞推dp)

hdu6170Two strings(第九場遞推dp)

Two strings

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1421    Accepted Submission(s): 584


Problem 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
Source 求兩串能否在兩個條件下匹配成功,a串只有大小寫,b串有大小寫,‘.’,‘*’,點代表可以成為任何字元,*代表可以讓前面字元出現任意次。 則將dp【ij】,設定為b串前i個字元和a串前j個字元匹配的結果,則dp[0][0]為1,那麼我們則有兩種情況 1.出現'點'符號,則有dp[i][j]=dp[i-1][j-1],兩個的前面相同就行了。 2.出現*符號,則如果a串中出現了a[i]==a[i-1],的話則代表b中字元要出現多次,也就是dp[i][j]=dp[i][j-1];  其次就是字元出現單次的情況了,那麼也就是dp[i][j]=dp[i-1][j];  還有一種情況,字元為空的情況,也就是a中當前字元我們可以不用看,直接dp[i][j-1]=dp[i-2[j-1]; \
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <vector>
#include <queue>
#define clr(i,n) for(int i=0;i<n;i++)
#define N 3050
using namespace std;
char s1[N];
char s2[N];
bool dp[N][N];
int main()
{
    int t;
    scanf("%d",&t);
    getchar();
    while(t--)
    {
        gets(s1+1);
        gets(s2+1);
        int len1=strlen(s1+1);
        int len2=strlen(s2+1);
        memset(dp,0,sizeof(dp));
        dp[0][0]=true;
        for(int i=1;i<=len2;i++)
        {
            for(int j=1;j<=len1;j++)
            {
                if(s2[i]=='.'||s1[j]==s2[i])
                {
                    dp[i][j]|=dp[i-1][j-1];
                }
                else if(s2[i]=='*')
                {
                    if(s1[j]==s1[j-1])
                    {
                        dp[i][j]|=dp[i][j-1];///多個相同字元
                    }
                    dp[i][j]|=dp[i-1][j];///*為單個字元
                    dp[i][j-1]|=dp[i-2][j-1];///空字元
                }
            }
        }
        if(dp[len2][len1])
        {
            cout<<"yes"<<endl;
        }
        else
        cout<<"no"<<endl;
    }
}