Deepest Parentheses Segments
EasyStack · Bloomberg
You are given a string text whose parentheses are balanced. Besides ( and ) it may contain letters, digits and spaces.
The depth of a parentheses pair is the number of pairs that contain it, counting itself, so a pair that is not inside any other pair has depth 1. Let D be the largest depth of any pair in text.
Return the substrings that lie strictly between the opening and closing parenthesis of every pair whose depth is D, ordered by where the pair appears from left to right. The returned substrings do not include the surrounding parentheses, and characters such as spaces are kept exactly. A pair at the maximum depth cannot contain another pair, so each returned substring contains no parentheses (it may be empty).
If text contains no parentheses, return an empty list.
Example 1
- Input:
- text = "x(ab(c)d(ef))(g(hi))"
- Output:
- ["c", "ef", "hi"]
- Explanation
- The pairs around
c,efandhiare each inside one other pair, so they have depth 2, the maximum. The outer pairs have depth 1 and are not reported.
Example 2
- Input:
- text = "(a)((b)c)"
- Output:
- ["b"]
- Explanation
(a)has depth 1. The pair aroundbsits inside((b)c), giving depth 2, sobis the only result.
Example 3
- Input:
- text = "no parens"
- Output:
- []
- Explanation
- There are no parentheses, so the result is empty.
Constraints
0 <= text.length <= 10^5textconsists of letters, digits, spaces,(and).- The parentheses in
textare balanced.