You are right to worry; I think that your end of the stick is very wrong and you solve the problem too literally (the information that the line does not exceed 1,000,000 characters is just so that people donβt worry about how slowly their code will work if the length was 100 times, and the examples are just examples - not the final list of strings you can expect to get)
I will not do the homework for you (by writing the code), but will give you a pointer to the solution that happens to me:
A line is correctly nested if each left bracket has a right bracket to the right of it or a correctly enclosed bracket between them. So, what about a recursive function or loop that deletes a string, matches "()". When your matches end, what are you left with? Nothing? Then it was a correctly nested string. Something else (for example, ')' or ') (' etc.) would mean that it was not properly nested in the first place.
source share