日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 385. 迷你语法分析器(栈)

發布時間:2024/7/5 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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. 迷你语法分析器(栈)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。