Typo
InterviewTime limit1sMemory limit128 MB
Given a bracket string with at most one typo, count how many single-character flips turn it into a valid balanced bracket string.
- Level
Medium5 of 10
- Topics
- String, Implementation, Prefix sum, Greedy
- Solved
- No attempts yet
Problem
Kipa loves valid bracket strings and recently bought a laptop. Because the keyboard was so small, Kipa worries that an opening bracket ( and a closing bracket ) might have been typed the wrong way around. Kipa typed very carefully, so there was at most one typo.
Given the bracket string Kipa typed, help Kipa by counting how many different positions there are at which changing a single character — turning an opening bracket into a closing bracket, or a closing bracket into an opening bracket — makes the whole string a valid bracket string.
A valid bracket string is defined as follows.
()is a valid bracket string.- If a string
Ais a valid bracket string, then(A)is also a valid bracket string. - If strings
AandBare both valid bracket strings, then their concatenationABis also a valid bracket string.
Input
The first line contains the bracket string Kipa typed. It consists only of ( and ), and its length satisfies .
Output
Print, on the first line, the number of positions at which changing exactly one character makes the string a valid bracket string. If there is no such position, print 0.
Hint
Consider the string ()(()))) that Kipa typed. The position of each character is shown below.
pos: 1 2 3 4 5 6 7 8
char: ( ) ( ( ) ) ) )
Changing the nd character ) to ( gives the valid bracket string (((()))). In the same way, changing the th, th, or th character also produces a valid bracket string, so the answer is .