Count The Repetitions in C++

C++Server Side ProgrammingProgramming

Suppose we have two non-empty strings s1 and s2 (maximum 100 characters) and two numbers n1 and n2 both are in range 0 to 106. Now suppose the strings S1 and S2, where S1=[s1,n1] and S2=[s2,n2].

S = [s,n] defines the string S which consists of n connected strings s. As an exdample, ["ab", 4] ="abababab".

On the other hand, we cal also define that string s1 can be obtained from string s2 if we remove some characters from s2 such that it becomes s1. So, "abc" can be obtained from "abdbec" based on the definition, but it can not be obtained from “acbbe”.

We have to find the maximum integer M such that [S2,M] can be obtained from S1.

So, if the input is like s1="acb", n1=4, s2="ab", n2=2, then the output will be 2

To solve this, we will follow these steps −

• for each character c in s2

• if c is not in s1 , then −

• return 0

• p1 := 0, p2 := 0, mark := 0

• while p1 < size of s1, do −

• c := s2[p2 mod size of s2]

• while (s1[p1 mod size of s1] is not equal to c and p1 < size of s1 *n1), do −

• (increase p1 by 1)

• (increase p2 by 1)

• (increase p1 by 1)

• if p2 mod size of s2 is same as 0, then −

• if p2 is same as size of s2, then −

• mark := p1

• otherwise when p1 mod size of s1 is same as mark mod size of s1, then −

• round := (size of s1 * n1 - p1) / (p1 - mark)

• p1 := p1 + round * (p1 - mark)

• p2 := p2 + round * (p2 - size of s2)

• return p2 / size of s2 / n2

Example

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int getMaxRepetitions(string s1, int n1, string s2, int n2) {
for (auto c : s2) {
if (s1.find(c) == string::npos)
return 0;
}
int p1 = 0, p2 = 0, mark = 0;
while (p1 < s1.length() * n1) {
char c = s2[p2 % s2.length()];
while (s1[p1 % s1.length()] != c && p1 <s1.length() * n1)
p1++;
p2++;
p1++;
if (p2 % s2.length() == 0) {
if (p2 == s2.length()) {
mark = p1;
}
else if (p1 % s1.length() == mark % s1.length()) {
int round = (s1.length() * n1 - p1) / (p1 - mark);
p1 += round * (p1 - mark);
p2 += round * (p2 - s2.length());
}
}
}
return p2 / s2.length() / n2;
}
};
main() {
Solution ob;
cout << (ob.getMaxRepetitions("acb",4,"ab",2));
}

"acb",4,"ab",2

2