How to successfully erase multiple characters from a string in inner loop !!
The expression i = max(-1LL, i - 2);
is used to adjust the index i
after removing two characters from the string and ensure that i
does not become less than -1
. Here’s what each part means:
Breakdown:
i - 2
:- After erasing two characters from the string at position
i
, we move the index back by 2 to account for the removed characters. - This is necessary because, after removing characters, we need to re-check the new characters that come into the current and previous positions.
- After erasing two characters from the string at position
-1LL
:- This represents the value
-1
as a long long data type (LL
suffix means "long long"). - The use of
-1
here is to ensure that after the adjustment, the indexi
doesn't become negative and out of bounds for the loop. Specifically, if we subtract 2 from a very low index (likei = 0
ori = 1
),i - 2
would result in a negative value like-1
or lower. - By limiting
i
to-1
at most, we prevent potential issues with indexing (e.g., accessing an invalid string position).
- This represents the value
max(-1LL, i - 2)
:- The
max
function returns the larger of the two values:-1LL
andi - 2
. - This ensures that
i
never goes below-1
. Ifi - 2
is less than-1
, it will return-1
, otherwise, it will returni - 2
.
- The
Why Use max(-1LL, i - 2)
:
- After erasing two characters, we move the index back to ensure we don't miss checking new adjacent characters.
- The
max
ensures thati
does not go out of bounds, particularly wheni
is close to the beginning of the string. Ifi
goes below-1
, it might cause invalid indexing in subsequent iterations.
Example:
Suppose i = 1
before erasing two characters:
i - 2
would be-1
.- The
max(-1LL, -1)
returns-1
. - This ensures that
i
is not set to a value lower than-1
, which could potentially cause errors.
In this case, setting i = -1
means that the next iteration will set i = 0
(since i++
happens at the end of the loop), so no character is skipped.
This is mainly a safeguard to prevent i
from going negative in a way that would break the program.
If you want to delete 3 chars then it will be i = max(-1ll,i-3)
Comments
Post a Comment