zoukankan      html  css  js  c++  java
  • [LeetCode] Mini Parser

    https://leetcode.com/problems/mini-parser/

    递归做法:不断找出一个完整的nested integer字符串,解析出来并add进NestedInteger结构。

    一个完整的nested integer字符串有以下两种情况:

    1. 没有[]包裹,形如 "123", "456" 的形式
    2. []包裹,形如 "[123, 456 , [], 789]" 的形式

    两种情况分别处理即可。

    class Solution {
    public:
        NestedInteger deserialize(string s) {
            if (s.empty()) return NestedInteger();
            if (s[0] != '[') return NestedInteger(stoi(s));
            
            NestedInteger ret;
            
            int pos = 1;
            if (s[pos] == ']') return ret;
            while (pos < s.size()) {
                int start = pos, end = pos;
                if (s[start] != '[') {
                    while (end < s.size() && s[end] != ',' && s[end] != ']') end++;
                } else {
                    int match = 1; end++;
                    while (match != 0) {
                        if (s[end] == '[') match++;
                        if (s[end] == ']') match--;
                        end++;
                    }
                }
                if (s[start] != '[') {
                    ret.add( NestedInteger(stoi(s.substr(start, end-start))) );
                } else {
                    ret.add( deserialize(s.substr(start, end-start)) );
                }
                pos = end + 1;
            }
            
            return ret;
        }
    };
    

    更清晰的写法:

    class Solution {
    public:
        NestedInteger deserialize(string s) {
            if (s.empty()) return NestedInteger();
            if (s[0] != '[') return NestedInteger(stoi(s));
            
            NestedInteger ret;
            
            int pos = 1;
            if (s[pos] == ']') return ret;
            
            while (pos < s.size()) {
                int start = pos, end = pos;
                string str = extract(s, start, end);
                if (s[start] != '[') {
                    ret.add( NestedInteger(stoi(str)) );
                } else {
                    ret.add ( deserialize(str) );
                }
                pos = end + 1;
            }
            
            return ret;
        }
        
        string extract(string& s, int& start, int& end) {
            if (s[start] != '[') {
                while (end < s.size() && s[end] != ',' && s[end] != ']') end++;
            } else {
                int match = 1; end++;
                while (match != 0) {
                    if (s[end] == '[') match++;
                    if (s[end] == ']') match--;
                    end++;
                }
            }
            return s.substr(start, end - start);
        }
    };
    
  • 相关阅读:
    内存优化
    OpenThreads库学习
    WPS/office使用技巧系列
    NB-IOT学习
    JSON和XML
    物联网平台学习
    .net提供的5种request-response方法一
    HTML5之IndexedDB使用详解
    jQuery圆形统计图实战开发
    用javascript将数据导入Excel
  • 原文地址:https://www.cnblogs.com/ilovezyg/p/6403600.html
Copyright © 2011-2022 走看看