|
| 1 | +# """ |
| 2 | +# This is the interface that allows for creating nested lists. |
| 3 | +# You should not implement it, or speculate about its implementation |
| 4 | +# """ |
| 5 | +#class NestedInteger: |
| 6 | +# def __init__(self, value=None): |
| 7 | +# """ |
| 8 | +# If value is not specified, initializes an empty list. |
| 9 | +# Otherwise initializes a single integer equal to value. |
| 10 | +# """ |
| 11 | +# |
| 12 | +# def isInteger(self): |
| 13 | +# """ |
| 14 | +# @return True if this NestedInteger holds a single integer, rather than a nested list. |
| 15 | +# :rtype bool |
| 16 | +# """ |
| 17 | +# |
| 18 | +# def add(self, elem): |
| 19 | +# """ |
| 20 | +# Set this NestedInteger to hold a nested list and adds a nested integer elem to it. |
| 21 | +# :rtype void |
| 22 | +# """ |
| 23 | +# |
| 24 | +# def setInteger(self, value): |
| 25 | +# """ |
| 26 | +# Set this NestedInteger to hold a single integer equal to value. |
| 27 | +# :rtype void |
| 28 | +# """ |
| 29 | +# |
| 30 | +# def getInteger(self): |
| 31 | +# """ |
| 32 | +# @return the single integer that this NestedInteger holds, if it holds a single integer |
| 33 | +# The result is undefined if this NestedInteger holds a nested list |
| 34 | +# :rtype int |
| 35 | +# """ |
| 36 | +# |
| 37 | +# def getList(self): |
| 38 | +# """ |
| 39 | +# @return the nested list that this NestedInteger holds, if it holds a nested list |
| 40 | +# The result is undefined if this NestedInteger holds a single integer |
| 41 | +# :rtype List[NestedInteger] |
| 42 | +# """ |
| 43 | + |
| 44 | +class Solution: |
| 45 | + def deserialize(self, s: str) -> NestedInteger: |
| 46 | + if s[0] != "[": |
| 47 | + return NestedInteger(int(s)) |
| 48 | + |
| 49 | + s = s[1:len(s)-1] |
| 50 | + n = len(s) |
| 51 | + |
| 52 | + def dfs(index): |
| 53 | + contains = NestedInteger() |
| 54 | + |
| 55 | + num = 0 |
| 56 | + is_positive = 1 |
| 57 | + has_num = False |
| 58 | + |
| 59 | + while index < n: |
| 60 | + if s[index] == "[": |
| 61 | + child, index = dfs(index + 1) |
| 62 | + contains.add(child) |
| 63 | + |
| 64 | + elif s[index] == "-": |
| 65 | + is_positive = -1 |
| 66 | + |
| 67 | + elif s[index].isdigit(): |
| 68 | + num = num * 10 + int(s[index]) |
| 69 | + has_num = True |
| 70 | + |
| 71 | + elif s[index] == ",": |
| 72 | + if has_num: |
| 73 | + contains.add(NestedInteger(num * is_positive)) |
| 74 | + num = 0 |
| 75 | + is_positive = 1 |
| 76 | + has_num = False |
| 77 | + |
| 78 | + elif s[index] == "]": |
| 79 | + if has_num: |
| 80 | + contains.add(NestedInteger(num * is_positive)) |
| 81 | + |
| 82 | + return contains, index |
| 83 | + |
| 84 | + index += 1 |
| 85 | + |
| 86 | + if has_num: |
| 87 | + if not is_positive: |
| 88 | + num *= -1 |
| 89 | + |
| 90 | + contains.add(NestedInteger(num)) |
| 91 | + |
| 92 | + return contains, index |
| 93 | + |
| 94 | + ans, _ = dfs(0) |
| 95 | + return ans |
0 commit comments