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 10^9+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 10^9+7.
Sample Input
eeettt
et
eeettt
te
Sample Output
9
0
题目大意:
判断鲍勃的弦是否是克莱尔弦的子序列,并输出鲍勃的弦在克莱尔的弦中作为子序列出现了多少次。注意:由于答案可能太大,您应该以10^9+7的模输出答案。
题目分析及思路:
动态规划求解,从前往后计算Clair的前i个字符有多少个子序列等于Bob的前j个字符(注意:遍历Bob序列需要从后向前遍历,否则因为输出的是最后一位的值,所以后面的字符会受到前面字符的影响导致结果错误)
AC代码:
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
const int mod=1e9+7;
int main()
{
string s1,s2;
while(cin>>s1>>s2)
{
long long a[100010];
memset(a,0,sizeof(a));
for(int i=0;i<s1.length();i++)
{
for(int j=s2.length()-1;j>=0;j--)
{
if(s1[i]==s2[j])
{
if(j==0)
{
a[j]++;
}
else
{
a[j]+=a[j-1];
}
}
a[j]=a[j]%mod;
}
}
cout<<a[s2.length()-1]<<endl;
}
}