C - String Game

 

题目

Clair and Bob play a game.Clair writes a string of lowercase characters, in which Bob sets the puzzle by selecting one of his favorite subsequence as the key word of the game. But Bob was so stupid that he might get some letters wrong.

Now Clair wants to know whether Bob’s string is a subsequence of Clair’s string. and how many times does Bob’s string appear as a subsequence in Clair’s string. As the answer maybe too large, you should output the answer modulo 109+7.

Input

The input may contain multiple test cases.

Each test case contains exactly two lines. 
The first line is Clair’s string, and the second line is Bob’s string. 
The length of both strings are no more than 5000.

 Output

For each test case, output one line, including a single integer representing how many times Bob’s string appears as a subsequence in Clair’s string.
The answer should modulo 109+7.

 Sample Input

eeettt
et
eeettt
te

 Sample Output

9
0
1
2


题意+翻译:

Clair和Bob玩了一个游戏。Clair写了一串小写字母,Bob通过选择一个他最喜欢的子序列作为游戏的关键字来设置谜题。
但是Bob太笨了,他可能把一些字母搞错了。
现在Clair想知道Bob的字符串是否是Clair的字符串的子序列。以及Bob的字符串作为Clair的字符串的子序列出现了多少次。
但是因为答案可能太大了,应该输出对(10的9次方+7)取模的结果。

输入样例:

输入可能包含多个测试用例。
每个测试用例包含两行。第一行是Clair的字符串,第二行是Bob的字符串。两个字符串的长度不超过5000


输出样例:

对于每个测试用例,输出一行,包括一个整数,表示Bob的字符串作为Clair的字符串的**子序列出现的次数**。
答案应该是对(10的9次方+7)取模。


解题思路

目的:给定字符串A 和字符串B 问B在A中子序列的出现次数

一开始我们想要使用遍历去计算子字符串出现的次数,就是按顺序一个一个的进行计算,后面发现计算量特别的大,于是后来使用动态规划这个算法

算法:动态规划
思路:

用dp计数,其中dp[i][j]代表着子字符串中前i个字母在长字符串的前j出现次数数
每次dp[i][j]=dp[i-1][j]继承过来
当a[i]==b[j]的时候 dp[i][j]+=dp[i-1][j-1] 所有的 dp[i][0]=1

代码实现

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e3+10;
const int mod=1e9+7;
int dp[maxn*5][maxn];
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    string a,b;
    while(cin>>a>>b)
    {
        memset(dp,0,sizeof(dp));
        int n=a.size(),m=b.size();
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=m;j++)
            {
                dp[i][j]=dp[i-1][j];
                if(a[i-1]==b[j-1])
                {
                    if(j==1)
                        dp[i][j]++;
                    else
                        dp[i][j]+=dp[i-1][j-1];
                }
                dp[i][j]%=mod;
            }
        }
        cout<<dp[n][m]<<endl;
    }
}

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值