LeetCode/solutions/385. Mini Parser.md
2019-12-20 13:26:17 +08:00

33 lines
1.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [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;
}
};
```