Shortest Regular Brackets Sequence
InterviewTime limit1sMemory limit128 MB
Given a string of brackets, find the length of the shortest regular bracket sequence that contains it as a subsequence.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Intervals, String, Implementation
- Solved
- No attempts yet
Problem
A regular brackets sequence is defined as follows.
- The empty sequence is a regular brackets sequence.
- If is a regular brackets sequence, then and are also regular brackets sequences.
- If and are regular brackets sequences, then their concatenation is also a regular brackets sequence.
For example, all of the following are regular brackets sequences:
(), [], (()), ([]), ()[], ()[()]
None of the following are regular brackets sequences:
(, [, ), )(, ([)], ([(]
You are given a string consisting of the four characters (, ), [, and ]. Among all regular brackets sequences that contain the given string as a subsequence, find the shortest one and report its length.
Here, a string is a subsequence of a string if there exist indices such that for every .
Input
The first line contains a string made up only of the characters (, ), [, and ]. The string has length at most and contains no other characters. The string may be empty (an empty line), which represents the empty sequence.
Output
Print a single integer: the length of the shortest regular brackets sequence that contains the given string as a subsequence.