time limit per test: 2 seconds memory limit per test: 256 megabytes
A newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word s2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.
For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions 1 and 5, we get a word "bcac".
Which least number of newspaper headings s1 will Fangy need to glue them, erase several letters and get word s2?
Input
The input data contain two lines. The first line contain the heading s1, the second line contains the word s2. The lines only consist of lowercase Latin letters (1≤|s1|≤104,1≤|s2|≤106).
Output
If it is impossible to get the word s2 in the above-described manner, print "-1" (without the quotes). Otherwise, print the least number of newspaper headings s1, which Fangy will need to receive the word s2.
Examples
Input
abc xyz
Output
-1
Input
abcd dabc
Output
2
看了网上的代码,对这种抽象方法解题还是不熟悉,其实就是两个字符串 s1和s2 s1可以无限的复制粘贴,看什么时候会有s2
这个字符串出现在s1中(根据题意可以知道,只要在s1中按顺序出现s2字符串的字符就满足题意)
那么可以得知 只有s2中所有的字符都出现在s1中,这个题就一定有解,反之就是 printf(“-1”)
代码思路:1、s2中的每个字符是否都存在,不存在则返回-1,代码结束
2、需要保存每个字符的索引 用s2中的字符进行匹配时要保证当前索引大于上一个索引
3、需要一个记录上一个索引的变量 last(初始化-1)
ex: s1=abcd
s2=dabc
下标:0 1 2 3
第一次:匹配d,d出现在 3 的位置 last =3
第二次:匹配a , a出现在 1 的位置 <last 所以 s1需要复制成 abcdabcd 下标为0 1 2 3 4 5 6 7
这时第二个a下标为 4 满足条件 last 更新为 4
…………
最终得到结果 :s1一共重复了几次
可以看到s1 是循环重复的 所以 当不匹配的时候可以将last再初始化为-1,就可以继续用s1了
#include<cstdio>
#include<set>
#include<cstring>
#include<iostream>
using namespace std;
int main()
{
string s1,s2;
cin>>s1>>s2;
set<int>s[30];
for(int i = 0; i < s1.length(); i++){
s[s1[i]-'a'].insert(i);
}
int last = -1,ans = 1;
for(int i = 0; i < s2.length(); i++){
int temp = s2[i]-'a';
if(s[temp].empty()){
cout<<"-1";
return 0;//对s2的每个字符进行判断,看是否存在
}
set<int> :: iterator it = s[temp].upper_bound(last);//函数就是找到第一个大于last的位置
if(it == s[temp].end()){
last = -1;
ans++;
}
last=*s[temp].upper_bound(last);
}
cout<<ans;
return 0;
}