All problems

Problem 298

Distinct Subsequences

Hard · 30 pts · String, Dynamic Programming

Problem

You are given two strings S and T. Count the number of ways to choose positions in S whose characters, read in order, spell exactly T. In other words, count the occurrences of T as a subsequence of S. Two ways are different if they use a different set of positions. Print the count modulo 1000000007. Let ways[j] be the number of ways to form the first j characters of T from the part of S read so far. For each character of S, go through j from |T| down to 1, and when S's character equals T[j - 1], add ways[j - 1] to ways[j]. Start with ways[0] = 1. Keep the counts in a 64-bit integer type (long long in C++, long in Java) and take the remainder after every addition and multiplication: adding or multiplying two remainders can be larger than a 32-bit int can hold (Python needs nothing special).

Input

Two lines: strings S and T (lowercase letters).

Output

Print the count modulo 1000000007.

Constraints

1 <= |S|, |T| <= 1000

Example input

rabbbit
rabbit

Example output

3

Explanation

"rabbbit" has three b's, and "rabbit" needs two of them. All the other letters are fixed, and there are 3 ways to choose two of the three b's, so the answer is 3.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Wildcard Matching Next: Palindrome Partitioning Minimum Cuts