[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);
    }
};
posted @ 2017-02-15 22:09  mioopoi  阅读(157)  评论(0编辑  收藏  举报