资讯专栏INFORMATION COLUMN

LeetCode[385] Mini Parser

Wuv1Up / 3264人阅读

摘要:复杂度思路每次遇到一个就推进去一个,每次碰到一个数字,就在。每次碰到一个右括号,就把出的,并将其压到栈顶的中。

LeetCode[385] Mini Parser

Given s = "[123,[456,[789]]]",

Return a NestedInteger object containing a nested list with 2 elements:

An integer containing value 123.

A nested list containing two elements:

An integer containing value 456.

A nested list with one element:

An integer containing value 789.

Using Stack

复杂度
O(N), O(N)

思路
每次遇到一个“["就推进去一个nextedinteger,每次碰到一个数字,就在stack.peek().add(number)。每次碰到一个右括号,就把pop()出peek()的nexted integer,并将其压到栈顶的nestedinteger中。

代码

public NestedInteger deserialize(String s) {
    // check the input string first;
    // .... if(s == null) return ..null 
    char[] arr = s.toCharArray();
    if(arr[0] != "[") return new NestedInteger(Integer.parseInt(s));
    Stack stack = new Stack<>();
    for(int i = 0; i < arr.length; i ++) {
        char ch = arr[i];
        if(ch == "[") {
            stack.push(new NestedInteger());
        }
        else if(ch == "]" && stack.size() > 1) {
            NestedInteger top = stack.pop();
            stack.peek().add(top);          
        }
        else if(Character.isDigit(ch) || ch == "-") {
            boolean pos = true;
            if(ch == "-") pos = false;
            int num = 0;
            while(i < arr.length && Character.isDigit(arr[i])) {
                num *= 10;
                num += arr[i] - "0";
                i ++;
            }
            // move i back to the integer, [788],
            // otherwise will skip the "]"
            i --;
            stack.peek().add(pos ? num : -num);
        }
    }
    return stack.pop();
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65262.html

相关文章

  • [LeetCode/LintCode] Design Twitter/Mini Twitter

    摘要:首先建立按时间戳从大到小排列的,找到中的,出其中在中存在的,把每一个的推特链表放入,再从中取头十条推特的放入结果数组。 Design Twitter Note 建立两个HashMap,一个存user,一个存tweets。以及整型的时间戳timestamp。user的k-v pair是userId-follower_set,tweets的k-v pair是userId-tweets_li...

    honmaple 评论0 收藏0
  • V5.NET:新客首单7折优惠,香港服务器低至325元/月,韩国独立服务器月付436元起

    摘要:怎么样本月商家韩国香港服务器香港服务器新客首单折,优惠后香港服务器最低港元元起,韩国服务器韩国服务器月付港元元起。v5.net怎么样?本月V5.NET商家韩国/香港服务器新客首单7折,优惠后香港服务器最低385港元(≈RMB325元)起,韩国服务器月付525港元(≈RMB436元)起。V5.NET是一家提供独立服务器租用和云服务器产品的商家,主要提供中国香港、台湾、日本、韩国等地区独立服务器...

    番茄西红柿 评论0 收藏2637
  • 容器最大盛水量

    摘要:容器最大盛水量给定个非负整数,,,,其中每个表示坐标,处的点。找到两条线,它们与轴一起形成一个容器,使得容器含有最多的水。 容器最大盛水量 Container With Most Water 给定n个非负整数a1,a2,...,an,其中每个表示坐标(i,ai)处的点。 绘制n条垂直线,使得线i的两个端点在(i,ai)和(i,0)处。 找到两条线,它们与x轴一起形成一个容器,使得容器...

    luckyw 评论0 收藏0
  • redis安装&&redis集群

    摘要:数据过期处理可以精确到毫秒的安装及部署部署环境需要系统,同样也有版本,可以练习使用。官方不典型支持。关闭进程正常关闭服务的地址端口号如果是本地服务,而且端口是这些参数可以省略。命令可以设置的有效期。修改端口,允许集群。 NoSql数据库之Redis1、什么是nosql,nosql的应用场景2、Nonsql数据库的类型a) Key-valueb) 文档型(类似于json)c) 列式存储d...

    岳光 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<