Reputation: 15
my code
#include<bits/stdc++.h>
using namespace std;
int main() {
int n ;
cin >> n;
string s1 , s2 , s3;
cin >> s1 >> s2;
string s = s1 + s1;
int count = 0;
for (int i = 0 ; s3 != s2 ; i++) {
// int a = s.find()
s3 = s.substr( i , s1.length() );
count++;
}
cout << count - 1;
return 0;
}
In this when I try to rotate the small sized string it is working fine but when I tried with some large length string it is showing error
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr: __pos (which is 227) > this->size() (which is 226)
I'm not understanding what is happening as with the string length of 20 or 30 it is working fine but when then string length is over the 110 it is showing this type of error.
Also this testcase is showing error
113 ndafmffmuuwjzqpquwjhuftohawpfegsjvnxwipwqlswvawogjuyiqtzsgpwgosegmuuhpzwchejuiitumyescxxyecnsatcbfpseqzowvdjyvchg zqpquwjhuftohawpfegsjvnxwipwqlswvawogjuyiqtzsgpwgosegmuuhpzwchejuiitumyescxxyecnsatcbfpseqzowvdjyvchgavqnonmkwgqp
Upvotes: 0
Views: 83
Reputation: 38062
This is quite simple your for
loop has condition which is never false
for this input. So you are increasing i
beyond size of s
(double of size of s1
).
Note common part of this two strings is: zqpquwjhuftohawpfegsjvnxwipwqlswvawogjuyiqtzsgpwgosegmuuhpzwchejuiitumyescxxyecnsatcbfpseqzowvdjyvchg
.
Difference is:
s1
has in front: ndafmffmuuwj
s2
has in backL: avqnonmkwgqp
So s1
is not rotation of s2
that is why codition in for
is never fasle
.
This is the reason std::basic_string::substr
throws an exception.
And here is better way to do it.
Upvotes: 1