LeetCode 385. 迷你语法分析器(栈)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 385. 迷你语法分析器(栈)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 題目
- 2. 解題
1. 題目
給定一個用字符串表示的整數的嵌套列表,實現一個解析它的語法分析器。
列表中的每個元素只可能是整數或整數嵌套列表
提示:你可以假定這些字符串都是格式良好的:
字符串非空 字符串不包含空格 字符串只包含數字0-9、[、-、,、] 示例 1: 給定 s = "324", 你應該返回一個 NestedInteger 對象,其中只包含整數值 324。示例 2: 給定 s = "[123,[456,[789]]]", 返回一個 NestedInteger 對象包含一個有兩個元素的嵌套列表:1. 一個 integer 包含值 123 2. 一個包含兩個元素的嵌套列表:i. 一個 integer 包含值 456ii. 一個包含一個元素的嵌套列表a. 一個 integer 包含值 789來源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/mini-parser
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
/*** // This is the interface that allows for creating nested lists.* // You should not implement it, or speculate about its implementation* class NestedInteger {* public:* // Constructor initializes an empty nested list.* NestedInteger();** // Constructor initializes a single integer.* NestedInteger(int value);** // Return true if this NestedInteger holds a single integer, rather than a nested list.* bool isInteger() const;** // Return the single integer that this NestedInteger holds, if it holds a single integer* // The result is undefined if this NestedInteger holds a nested list* int getInteger() const;** // Set this NestedInteger to hold a single integer.* void setInteger(int value);** // Set this NestedInteger to hold a nested list and adds a nested integer to it.* void add(const NestedInteger &ni);** // Return the nested list that this NestedInteger holds, if it holds a nested list* // The result is undefined if this NestedInteger holds a single integer* const vector<NestedInteger> &getList() const;* };*/ class Solution { public:NestedInteger deserialize(string s) {if(s[0] != '[')return NestedInteger(stoi(s));stack<NestedInteger> stk;string num;for(int i = 0; i < s.size(); ++i){if(s[i] == '[')stk.push(NestedInteger());else if(isdigit(s[i]) || s[i]=='-'){num += s[i];}else // , ]{if(!num.empty()){stk.top().add(NestedInteger(stoi(num)));num.clear();}if(s[i]==']' && stk.size()>1){NestedInteger t = stk.top();stk.pop();stk.top().add(t);}}}return stk.top();} };16 ms 11.2 MB C++
我的CSDN博客地址 https://michael.blog.csdn.net/
長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
總結
以上是生活随笔為你收集整理的LeetCode 385. 迷你语法分析器(栈)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Scala 入门1(变量、分支循环、函数
- 下一篇: Spark IDEA 编程环境配置