Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 696600d

Browse files
Create Strings of Impurity Explanation.txt
1 parent eaabdc1 commit 696600d

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
We will be greedy in constructing the string.
2+
3+
1. Initially we have matches 0 characters
4+
2. We will then look for the earliest location of T[0]
5+
3. Then, we will look for the earliest location in [0, n] in S for T[0]. Let this position be p.
6+
4. Then, we will look for the earliest location in [p, n] in S for T[1]
7+
5. If T[1] is not present in [p, n] but is in [0, p - 1], we will go back and start another subsequence.
8+
9+
-----
10+
11+
After that the length of the string we need is = (No_of_Concatenations)|S| + Matched_Prefix
12+
13+
-----
14+
15+
int main()
16+
{
17+
string S, T;
18+
cin >> S >> T;
19+
20+
const int NO_OF_ALPHABETS = 26;
21+
vector <vector <int> > locations(NO_OF_ALPHABETS);
22+
for(int i = 0; i < S.size(); i++)
23+
{
24+
locations[S[i] - 'a'].push_back(i);
25+
}
26+
27+
int no_of_concatenations = 1, matched_prefix = -1;
28+
for(int i = 0; i < T.size(); i++)
29+
{
30+
if(locations[T[i] - 'a'].size() == 0)
31+
{
32+
cout << "-1\n";
33+
34+
return 0;
35+
}
36+
37+
auto it = upper_bound(locations[T[i] - 'a'].begin(), locations[T[i] - 'a'].end(), matched_prefix);
38+
39+
if(it == locations[T[i] - 'a'].end())
40+
{
41+
no_of_concatenations++;
42+
43+
matched_prefix = locations[T[i] - 'a'][0];
44+
}
45+
else
46+
{
47+
matched_prefix = *it;
48+
}
49+
}
50+
51+
long long final_length = (no_of_concatenations - 1)*1LL*S.size() + (matched_prefix + 1);
52+
cout << final_length << "\n";
53+
54+
return 0;
55+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /