Golang | Leetcode Golang题解之第385题迷你语法分析器

[复制链接]
发表于 2026-1-26 06:19:17 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
标题:

题解:
  1. func deserialize(s string) *NestedInteger {
  2.     if s[0] != '[' {
  3.         num, _ := strconv.Atoi(s)
  4.         ni := &NestedInteger{}
  5.         ni.SetInteger(num)
  6.         return ni
  7.     }
  8.     stack, num, negative := []*NestedInteger{}, 0, false
  9.     for i, ch := range s {
  10.         if ch == '-' {
  11.             negative = true
  12.         } else if unicode.IsDigit(ch) {
  13.             num = num*10 + int(ch-'0')
  14.         } else if ch == '[' {
  15.             stack = append(stack, &NestedInteger{})
  16.         } else if ch == ',' || ch == ']' {
  17.             if unicode.IsDigit(rune(s[i-1])) {
  18.                 if negative {
  19.                     num = -num
  20.                 }
  21.                 ni := NestedInteger{}
  22.                 ni.SetInteger(num)
  23.                 stack[len(stack)-1].Add(ni)
  24.             }
  25.             num, negative = 0, false
  26.             if ch == ']' && len(stack) > 1 {
  27.                 stack[len(stack)-2].Add(*stack[len(stack)-1])
  28.                 stack = stack[:len(stack)-1]
  29.             }
  30.         }
  31.     }
  32.     return stack[len(stack)-1]
  33. }
复制代码
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表