原题:
C. Obtain The String
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given two strings s
and t consisting of lowercase Latin letters. Also you have a string z which is initially empty. You want string z to be equal to string t. You can perform the following operation to achieve this: append any subsequence of s at the end of string z. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=ac, s=abcde, you may turn z
into following strings in one operation:
z=acace
(if we choose subsequence ace);
z=acbcd
(if we choose subsequence bcd);
z=acbce
(if we choose subsequence bce).
Note that after this operation string s doesn’t change.
Calculate the minimum number of such operations to turn string z
into string t.
Input
The first line contains the integer T (1≤T≤100) — the number of test cases.
The first line of each testcase contains one string s (1≤|s|≤10^5) consisting of lowercase Latin letters.
The second line of each testcase contains one string t (1≤|t|≤10^5) consisting of lowercase Latin letters.
It is guaranteed that the total length of all strings s and t in the input does not exceed 2⋅10^5.
Output
For each testcase, print one integer — the minimum number of operations to turn string z into string t. If it’s impossible print −1.
Example
Input
3
aabce
ace
abacaba
aax
ty
yyt
Output
1
-1
3
中文:
给你两个字符串s和t,现在让你每次取s的子串,连接到z串上,使得z与t相同,z初始为空。其中s的子串为在s中删除0个或多个字符串后得到的字符串,问你最少添加多少次。
代码:
#include
#include
#include
#include
#include
#include
using namespace std;
const int maxn = 10000 + 1;
vector<int> mark[26];
int st[26];
string s, t;
int n;
int main()
{
ios::sync_with_stdio(false);
cin >> n;
while (n--) {
cin >> s >> t;
for (int i = 0; i<26; i++)
mark[i].clear();
for (int i = 0; i<s.size(); i++) {
mark[s[i] - 'a'].push_back(i);
}
int ans = 1;
memset(st, 0, sizeof(st));
int pre;
for (int i = 0; i < t.size();) {
if (mark[t[i] - 'a'].empty()) {
ans = -1;
break;
}
if (i == 0) {
pre = mark[t[i] - 'a'].front();// 保存当前下标
st[t[i]-'a']++;
i++;
}
else {
int flag = 0;
if (st[t[i] - 'a'] >= mark[t[i] - 'a'].size()) {
flag = 1;
}
if (!flag) {
// 找大于pre的第一个数的下标
int ind = lower_bound(mark[t[i] - 'a'].begin() + st[t[i] - 'a'], mark[t[i] - 'a'].end(), pre + 1) - mark[t[i] - 'a'].begin();
if (ind == mark[t[i] - 'a'].size()) {
flag = 1;
}
if (!flag) {
pre = mark[t[i] - 'a'][ind];
st[t[i] - 'a'] = ind + 1;
i++;
}
}
if(flag) {
pre = -1;
ans++;
memset(st, 0, sizeof(st));
}
}
}
cout << ans << endl;
}
return 0;
}
/*
2
abab
baabaa
abacabadabacaba
baabaab
*/
解答:
首先把字符串s每个字符对应的下标存储在一个哈希里面,如程序中的mark
遍历字符串t[i],每次在mark中寻找t[i]在s中对应的下标,因为要找s中的子串,t[i]寻找字符串s中对应的下标一定要大于t[i-1]字符在s中对应的下标,且t[i]在mark中对应的下标要与t[i-1]在mark中对应的下标尽量的靠近(贪心),这里可以使用二分的方式每次寻找字符对应的下标即可。