Get array's depth in JavaScript

前端 未结 6 2062
慢半拍i
慢半拍i 2020-12-11 08:25

In order to get the array\'s depth I thought I can use the flat() method like so:

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-11 08:47

    Convert the array to string lets assume We are given a string having parenthesis like below “( ((X)) (((Y))) )” We need to find the maximum depth of string, like 4 in above example. Since ‘Y’ is surrounded by 4 balanced parenthesis.

    Take two variables max and current_max, initialize both of them as 0. Traverse the string, do following for every character a) If current character is ‘(’, increment current_max and update max value if required. b) If character is ‘)’ means we previously had a ‘(’ character so decrement current_max without worry but dont reduce max value .

    If current_max is greater than max then update max value to current_max at that instance. after traverse is completed the max is is the depth of the array.

提交回复
热议问题