From 1540531700ea18cc5e8a94015ef617d4d85c9ca5 Mon Sep 17 00:00:00 2001 From: ShusenTang Date: Fri, 20 Dec 2019 13:26:17 +0800 Subject: [PATCH] Create 385. Mini Parser.md --- solutions/385. Mini Parser.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 solutions/385. Mini Parser.md diff --git a/solutions/385. Mini Parser.md b/solutions/385. Mini Parser.md new file mode 100644 index 0000000..7ebcf6d --- /dev/null +++ b/solutions/385. Mini Parser.md @@ -0,0 +1,32 @@ +# [385. Mini Parser](https://leetcode.com/problems/mini-parser/) + +# 思路 +题目要求实现一个迷你解析器用来把一个字符串解析成一个嵌套整数类。根据这个嵌套整数类的定义,我们可以用递归来做。 + +* 递归出口:字符串s就代表一个整数,那么直接返回即可。 +* 否则,即s以'['开头,那么他就是一个列表,我们应该从前往后遍历s然后递归调用下去。这个过程中,我们用两个指针l和r来表示子串的边界; +另外要注意用一个计数器count来记录遇到的括号以保证括号是配对的,每当遇到'['就count++,每当遇到']'就count--。只有当count=0时l和r之间的子串才是合法的。 + +# C++ +``` C++ +class Solution { +public: + NestedInteger deserialize(string s) { + if(s[0] != '[') return NestedInteger(stoi(s)); + + NestedInteger res; + int l = 1, r = 1, count = 0; + while(r < s.size()){ + if(s[r] == '[') count++; + else if(s[r] == ']') count--; + + if((s[r] == ',' && count == 0) || r == s.size() - 1){ + if(l < r) res.add(deserialize(s.substr(l, r-l))); + l = r + 1; + } + r++; + } + return res; + } +}; +```