【LeetCode每日一题打卡】385. 迷你语法分析器

103 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第5天,点击查看活动详情

LeetCode每日一题打卡专栏正式启动!不出意外将日更LeetCode的每日一题,敬请期待。

个人博客链接:bbstudy.net/ (等毕业论文做好后续会完善相关功能)

4.15:迷你语法分析器

LeetCode 385,点击题目可直接跳转至LeetCode

题解:dfs或栈

今天题目可能有点小复杂,但难度不大,可以理解为模拟。

可以使用dfs和栈来实现,dfs思路比较简单,但是相比于栈比较复杂,于是在此用栈来模拟实现。

栈中元素保存的是NestedInteger对象。

每一个NestedInteger对象存在两个元素:整数 或 列表

  • 当出现 [[ 字符时,则表示创建新的NestedInteger对象

  • 当出现 ,,]] 字符时,表示要创建新的元素或对象

    • 如果是 ,, 则表示此时是一个列表,把上一个整数添加至栈顶元素的列表中
    • 如果是 ]] 则此时NestedInteger对象已经结束,添加至栈顶

最后只需要返回栈顶元素即可。具体见代码。

注意:如果只有一个整数表示的情况,如示例1,则需要特判下。

C++代码

/**
 * // 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]!='['){  //只有一个数字的情况,如示例1
            return NestedInteger(stoi(s));   //stoi():c++内置string to int函数
        }
        stack<NestedInteger> sta;
        int n=s.length();
        bool flag=0;   //记录正负
        int num=0;
        for(int i=0;i<n;i++){
            if(s[i]=='-') flag=1;
            else if(isdigit(s[i])){  // c++内置判断是否为数字函数
                num=num*10+(s[i]-'0');
            }else if(s[i]=='['){   //创建一个新的对象
                sta.push(NestedInteger());
            }else if(s[i]==','||s[i]==']'){   //新的元素或对象
                if(isdigit(s[i-1])){
                    if(flag) num=-num;
                    sta.top().add(NestedInteger(num));
                }
                num=0;flag=0;
                if(s[i]==']'&&sta.size()>1){
                    NestedInteger ni=sta.top();
                    sta.pop();
                    sta.top().add(ni);
                }
            }
        }
        return sta.top();
    }
};