Skip to content

Commit d39fe78

Browse files
committed
Solve problems 18. Concatenated String from CS Academy
1 parent 602e31d commit d39fe78

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
Idea:
3+
- Build next array for string `a`, then using it iterate over string `b`
4+
and each time try to find the current character `b[i]`, if you cannot
5+
find it then return to the beginning of the string `a` and try to find
6+
it again.
7+
*/
8+
9+
#include <bits/stdc++.h>
10+
11+
using namespace std;
12+
13+
int const N = 1e5 + 1;
14+
int k = 1, nxt[N][26];
15+
bool vis[26];
16+
string a, b;
17+
18+
int main() {
19+
cin >> a >> b;
20+
21+
for(int i = 0; i < a.length(); ++i)
22+
vis[a[i] - 'a'] = true;
23+
for(int i = 0; i < b.length(); ++i)
24+
if(!vis[b[i] - 'a']) {
25+
cout << -1 << endl;
26+
return 0;
27+
}
28+
29+
memset(nxt, -1, sizeof nxt);
30+
for(int i = a.length() - 2; i >= 0; --i) {
31+
for(int j = 0; j < 26; ++j)
32+
nxt[i][j] = nxt[i + 1][j];
33+
nxt[i][a[i + 1] - 'a'] = i + 1;
34+
}
35+
36+
for(int i = 0, whr = -1; i < b.length(); ++i) {
37+
char cur = b[i];
38+
39+
if(whr == -1) {
40+
if(a[0] == cur)
41+
whr = 0;
42+
else
43+
whr = nxt[0][cur - 'a'];
44+
} else {
45+
if(nxt[whr][cur - 'a'] != -1)
46+
whr = nxt[whr][cur - 'a'];
47+
else
48+
whr = -1, ++k, --i;
49+
}
50+
}
51+
52+
cout << k << endl;
53+
54+
return 0;
55+
}

CS Academy/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# Problems links
22

3+
- [18. Concatenated String](https://csacademy.com/contest/round-18/task/concatenated-string/)
34
- [18. Consecutive Digits Signs](https://csacademy.com/contest/round-18/task/consecutive-digit-signs/)
45
- [24. Vector Size](https://csacademy.com/contest/round-24/#task/vector-size)
56
- [24. Kth Special Number](https://csacademy.com/contest/round-24/#task/kth-special-number)

0 commit comments

Comments
 (0)