1 solutions

  • 1
    @ 2023-12-2 21:55:00

    思路:

    一道简单的dp: 首先初始化,对于两个字符串a,b;和一个二维数组ans表示我们判断到a[i]与b[j];当我们a[i]==b[j],此时ans[i][j] = ans[i - 1][j - 1]+1(dp中的状态转移);当a[i] != b[j]时,此时ans[i][j] = max (ans[i - 1][j],ans[i][j - 1]);这里就需要花两秒钟思考一下,当不相等的时候应该由那个状态转移过来?划一个图就好理解了。字符串abcd,efbd;这里对表格边界特殊处理。

    e f b d
    0 0
    a
    b 1 1
    c
    d 2

    AC代码:

    #include<bits/stdc++.h>
    #define ll long long
    using namespace std;
    string a,b;
    int ans[222][222];//ans[i][j]用来表示判断到a[i]和b[j] 
    int temp1,temp2;
    int main ()
    {
    	while (cin >> a >> b)
    	{
    		memset(ans,0,sizeof(ans));
    		temp1 = a.length();
    		temp2 = b.length();
    		for(int i = 1;i <= temp1;++ i)
    		{
    			for(int j = 1;j <= temp2;++ j)
    			{
    				if(a[i - 1] == b[j - 1])
    				{
    					ans[i][j] = ans[i - 1][j - 1] + 1;
    				}
    				else {
    					ans[i][j] = max (ans[i - 1][j],ans[i][j - 1]);
    				}
    			}
    		}
    		cout << ans[temp1][temp2] <<"\n";
    	}
    
    
    	return 0;
    }
    

    Information

    ID
    6868
    Time
    1000ms
    Memory
    128MiB
    Difficulty
    10
    Tags
    (None)
    # Submissions
    4
    Accepted
    2
    Uploaded By