首页 > 试题广场 >

获取n维数组的最大深度

[编程题]获取n维数组的最大深度
  • 热度指数:4070 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
输入参数为字符串型的n维数组,数组的每一项值为数组 或 int型数字。请实现一个函数,可以获取列表嵌套列表的最大深度为多少。

输入描述:
输入参数为字符串型的 n维数组,列表的每一项值为数组 或 int型数字。数组内的数组,每一项值,也可以是数组 或 int型数字。


输出描述:
int型数字,表示数组嵌套的深度。
示例1

输入

[[1], [2,3,4], [5,[2,3]], [7], [0,[1,2,3,4],3,5], [1,3], [3,2,4]]

输出

3

说明

n维数组的深度为3
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

const int MAX_N = 1 << 16; // 65536

int main(const int argc, const char* const argv[]) {
  char input[MAX_N] = "";
  gets(input);
  
  char stk[20];
  int top = -1, ans = 0;
  
  const char* p = input;
  while (*p) {
    switch (*p) {
      case '[':
        *(stk + ++top) = '[';
        ans = fmax(ans, top + 1);
        break;
      case ']':
        --top;
        break;
      default:
        break;
    }
    ++p;
  }
  
  assert(top == -1);
  return fprintf(stdout, "%d", ans),  0;
}

发表于 2021-07-19 12:08:38 回复(0)