I am trying to solve the problem "Kick Start" from round G from last year. In short you need to count the number of appearances of the substring "KICK....START" with any number of characters in between the two words. The input is a string with only capital letters.
I wrote some code and the sample works fine. But after sending the code I get a runtime error in the first test case. I Have tried many different things like using the at() function from string, or substring but nothing has solved the problem. Any ideas what the problem could be?
So my function that gets the error looks like this:
long long fragment_count = 0;
long long open_count = 0;
string text;
cin >> text;
for (int i = 0; i < text.size() - 4; ++i) {
if (text[i] == 'K') {
if (text[i + 1] == 'I' && text[i + 2] == 'C' && text[i + 3] == 'K') {
open_count++;
}
} else if (text[i] == 'S') {
if (text[i + 1] == 'T' && text[i + 2] == 'A' && text[i + 3] == 'R' && text[i + 4] == 'T') {
fragment_count += open_count;
}
}
}
cout << fragment_count << "\n";
Edit: Outside of this function is the template I use for the kickstart problems. At the start there are two lines that I read that speed up io:
ios::sync_with_stdio(0);
cin.tie(0);
Then I just read a number with cin, that signifies the test cases and call the fucntion above for every test case.
text.size()
is of type std::size_t
, which is an unsigned type. If the length of the text is less than 4, text.size() - 4
wraps around and becomes a huge positive number.
Replace the comparison with i + 4 < text.size()
.