Parse and Sum a Depth-Weighted Nested List
Problem statement
You are given a valid bracketed string nestedList representing a nested list of signed integers. Lists use square brackets, elements are comma-separated, and optional spaces may appear anywhere outside an integer token.
The outermost list has depth 1. Each nested list increases the depth of its integer elements by one. Return the sum of every integer multiplied by its depth.
Your parser must handle multi-digit values, optional minus signs, closing brackets, and an integer immediately followed by the end of the string.
Function
depthSum(nestedList: String) → intExamples
Example 1
nestedList = "[3, 8, [2, 14], [2, [91]]]"return = 320The weighted sum is 3 + 8 + 2*2 + 14*2 + 2*2 + 91*3 = 320.
Example 2
nestedList = "[1,[4,[6]]]"return = 27The weighted sum is 1*1 + 4*2 + 6*3 = 27.
Example 3
nestedList = "[-12, [5], 10]"return = 8The integers contribute -12*1 + 5*2 + 10*1 = 8.
Constraints
nestedListis a syntactically valid list expression.- Every integer token fits in a signed
32-bit integer. - The final weighted sum fits in a signed
32-bit integer.