Depth-Weighted Sum of a Nested List
Problem statement
You get a list written as text, for example [3,[5,-2],[[4]]]. Its items are integers and smaller lists, and those smaller lists can hold more lists, mixed with integers, many levels deep.
Give each integer a weight equal to how many lists enclose it: integers placed directly in the outer list get weight 1, those one list further in get weight 2, and so on.
Return the sum of every integer times its weight.
Function
depthSum(nestedList: String) → intExamples
Example 1
nestedList = "[3,[5,-2],[[4]]]"return = 213 is inside one list (depth 1), 5 and -2 are inside two (depth 2), and 4 is inside three (depth 3): 3 x 1 + 5 x 2 + (-2) x 2 + 4 x 3 = 3 + 10 - 4 + 12 = 21.
Example 2
nestedList = "[[],7,[[]]]"return = 7Empty lists hold no integers and add nothing. Only 7 counts, at depth 1: the sum is 7.
Example 3
nestedList = "[[[10]],[[-10]],1]"return = 110 and -10 are both at depth 3 and cancel out (30 - 30 = 0); 1 at depth 1 adds 1. The sum is 1.
Constraints
2 <= nestedList.length <= 5000nestedListis one list written as compact text: square brackets, commas and integers only, with no spaces (empty lists such as[]are allowed)- every integer is between
-100and100, written without leading zeros or a plus sign - lists are nested at most
50deep (the outer list is depth 1)