mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 385. Mini Parser.md
This commit is contained in:
parent
aff96849ab
commit
1540531700
32
solutions/385. Mini Parser.md
Normal file
32
solutions/385. Mini Parser.md
Normal file
@ -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;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
Loading…
Reference in New Issue
Block a user