1196. Nesting Depth Outside Quotes
A config linter reads JSON-like text and reports how deeply it is nested. Only the brackets [ and { (and their closers ] and }) count, and only when they sit outside string literals. A literal runs between double quotes, and inside it a backslash escapes the next character, so \" does not end the literal and \\ is a single escaped backslash.
Return the maximum nesting depth reached by brackets outside literals, or 0 if there are none. Brackets outside literals are balanced and every literal is closed. All other characters are ignored.
A single left-to-right scan with a depth counter and an in-literal flag gives O(n) time and O(1) extra space.
Example 1
- Input:
- s = "{\"a\": [1, 2]}"
- Output:
- 2
- Explanation:
The object holds an array, so the deepest point is 2.
Example 2
- Input:
- s = "\"[[[\""
- Output:
- 0
- Explanation:
Every bracket sits inside a string literal, so the depth is 0.
Example 3
- Input:
- s = "[{\"k\":\"]\"}, [[]]]"
- Output:
- 3
- Explanation:
The path [ [ [ reaches depth 3 in the second element; the ] in the literal is ignored.
Constraints
1 ≤ s.length ≤ 104
printable ASCII
string literals are closed; brackets outside literals are balanced
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(1)