385. 迷你语法分析器
给定一个字符串 s 表示一个整数嵌套列表,实现一个解析它的语法分析器并返回解析的结果 NestedInteger
。
列表中的每个元素只可能是整数或整数嵌套列表
示例 1:
输入:s = "324", 输出:324 解释:你应该返回一个 NestedInteger 对象,其中只包含整数值 324。
示例 2:
输入:s = "[123,[456,[789]]]", 输出:[123,[456,[789]]] 解释:返回一个 NestedInteger 对象包含一个有两个元素的嵌套列表: 1. 一个 integer 包含值 123 2. 一个包含两个元素的嵌套列表: i. 一个 integer 包含值 456 ii. 一个包含一个元素的嵌套列表 a. 一个 integer 包含值 789
提示:
1 <= s.length <= 5 * 104
s
由数字、方括号 "[]"
、负号 '-'
、逗号 ','
组成s
是可解析的 NestedInteger
[-106, 106]
原站题解
python3 解法, 执行用时: 48 ms, 内存消耗: 18.5 MB, 提交时间: 2022-12-09 10:06:08
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger: # def __init__(self, value=None): # """ # If value is not specified, initializes an empty list. # Otherwise initializes a single integer equal to value. # """ # # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def add(self, elem): # """ # Set this NestedInteger to hold a nested list and adds a nested integer elem to it. # :rtype void # """ # # def setInteger(self, value): # """ # Set this NestedInteger to hold a single integer equal to value. # :rtype void # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class Solution: def deserialize(self, s: str) -> NestedInteger: # 纯数字 if s[0] != '[': return NestedInteger(int(s)) stack, curVal, sign = [], 0, False for i, c in enumerate(s): match c: case '[': # 递归嵌套 stack.append(NestedInteger()) case '-': # 数字符号 sign = True case ',': # 只有上一个字符是数字才加入了新的数字,否则可能是 "]," if s[i - 1].isdigit(): stack[-1].add(NestedInteger(-curVal if sign else curVal)) curVal, sign = 0, False case ']': # 只有上一个字符是数字才加入了新的数字,否则可能是 "[]" if s[i - 1].isdigit(): stack[-1].add(NestedInteger(-curVal if sign else curVal)) # 弹出栈,并将当前的对象加入嵌套的列表中 if len(stack) > 1: cur = stack.pop() stack[-1].add(cur) curVal, sign = 0, False case _: # 数字计算 curVal = curVal * 10 + int(c) return stack.pop()
python3 解法, 执行用时: 68 ms, 内存消耗: 18.5 MB, 提交时间: 2022-12-09 10:01:25
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger: # def __init__(self, value=None): # """ # If value is not specified, initializes an empty list. # Otherwise initializes a single integer equal to value. # """ # # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def add(self, elem): # """ # Set this NestedInteger to hold a nested list and adds a nested integer elem to it. # :rtype void # """ # # def setInteger(self, value): # """ # Set this NestedInteger to hold a single integer equal to value. # :rtype void # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class Solution: def deserialize(self, s: str) -> NestedInteger: index = 0 def dfs() -> NestedInteger: nonlocal index if s[index] == '[': index += 1 ni = NestedInteger() while s[index] != ']': ni.add(dfs()) if s[index] == ',': index += 1 index += 1 return ni else: negative = False if s[index] == '-': negative = True index += 1 num = 0 while index < len(s) and s[index].isdigit(): num *= 10 num += int(s[index]) index += 1 if negative: num = -num return NestedInteger(num) return dfs()
java 解法, 执行用时: 1 ms, 内存消耗: 41.5 MB, 提交时间: 2022-12-09 10:01:08
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * public interface NestedInteger { * // Constructor initializes an empty nested list. * public NestedInteger(); * * // Constructor initializes a single integer. * public NestedInteger(int value); * * // @return true if this NestedInteger holds a single integer, rather than a nested list. * public boolean isInteger(); * * // @return the single integer that this NestedInteger holds, if it holds a single integer * // Return null if this NestedInteger holds a nested list * public Integer getInteger(); * * // Set this NestedInteger to hold a single integer. * public void setInteger(int value); * * // Set this NestedInteger to hold a nested list and adds a nested integer to it. * public void add(NestedInteger ni); * * // @return the nested list that this NestedInteger holds, if it holds a nested list * // Return empty list if this NestedInteger holds a single integer * public List<NestedInteger> getList(); * } */ class Solution { int index = 0; public NestedInteger deserialize(String s) { if (s.charAt(index) == '[') { index++; NestedInteger ni = new NestedInteger(); while (s.charAt(index) != ']') { ni.add(deserialize(s)); if (s.charAt(index) == ',') { index++; } } index++; return ni; } else { boolean negative = false; if (s.charAt(index) == '-') { negative = true; index++; } int num = 0; while (index < s.length() && Character.isDigit(s.charAt(index))) { num = num * 10 + s.charAt(index) - '0'; index++; } if (negative) { num *= -1; } return new NestedInteger(num); } } }
javascript 解法, 执行用时: 112 ms, 内存消耗: 55.2 MB, 提交时间: 2022-12-09 10:00:53
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * function NestedInteger() { * * Return true if this NestedInteger holds a single integer, rather than a nested list. * @return {boolean} * this.isInteger = function() { * ... * }; * * Return the single integer that this NestedInteger holds, if it holds a single integer * Return null if this NestedInteger holds a nested list * @return {integer} * this.getInteger = function() { * ... * }; * * Set this NestedInteger to hold a single integer equal to value. * @return {void} * this.setInteger = function(value) { * ... * }; * * Set this NestedInteger to hold a nested list and adds a nested integer elem to it. * @return {void} * this.add = function(elem) { * ... * }; * * Return the nested list that this NestedInteger holds, if it holds a nested list * Return null if this NestedInteger holds a single integer * @return {NestedInteger[]} * this.getList = function() { * ... * }; * }; */ /** * @param {string} s * @return {NestedInteger} */ var deserialize = function(s) { let index = 0; const dfs = (s) => { if (s[index] === '[') { index++; const ni = new NestedInteger(); while (s[index] !== ']') { ni.add(dfs(s)); if (s[index] === ',') { index++; } } index++; return ni; } else { let negative = false; if (s[index] === '-') { negative = true; index++; } let num = 0; while (index < s.length && isDigit(s[index])) { num = num * 10 + s[index].charCodeAt() - '0'.charCodeAt(); index++; } if (negative) { num *= -1; } return new NestedInteger(num); } } return dfs(s); }; const isDigit = (ch) => { return parseFloat(ch).toString() === "NaN" ? false : true; }
golang 解法, 执行用时: 4 ms, 内存消耗: 4.9 MB, 提交时间: 2022-12-09 10:00:35
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * type NestedInteger struct { * } * * // Return true if this NestedInteger holds a single integer, rather than a nested list. * func (n NestedInteger) IsInteger() bool {} * * // Return the single integer that this NestedInteger holds, if it holds a single integer * // The result is undefined if this NestedInteger holds a nested list * // So before calling this method, you should have a check * func (n NestedInteger) GetInteger() int {} * * // Set this NestedInteger to hold a single integer. * func (n *NestedInteger) SetInteger(value int) {} * * // Set this NestedInteger to hold a nested list and adds a nested integer to it. * func (n *NestedInteger) Add(elem NestedInteger) {} * * // Return the nested list that this NestedInteger holds, if it holds a nested list * // The list length is zero if this NestedInteger holds a single integer * // You can access NestedInteger's List element directly if you want to modify it * func (n NestedInteger) GetList() []*NestedInteger {} */ func deserialize(s string) *NestedInteger { index := 0 var dfs func() *NestedInteger dfs = func() *NestedInteger { ni := &NestedInteger{} if s[index] == '[' { index++ for s[index] != ']' { ni.Add(*dfs()) if s[index] == ',' { index++ } } index++ return ni } negative := s[index] == '-' if negative { index++ } num := 0 for ; index < len(s) && unicode.IsDigit(rune(s[index])); index++ { num = num*10 + int(s[index]-'0') } if negative { num = -num } ni.SetInteger(num) return ni } return dfs() }
golang 解法, 执行用时: 4 ms, 内存消耗: 4.3 MB, 提交时间: 2022-12-09 10:00:19
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * type NestedInteger struct { * } * * // Return true if this NestedInteger holds a single integer, rather than a nested list. * func (n NestedInteger) IsInteger() bool {} * * // Return the single integer that this NestedInteger holds, if it holds a single integer * // The result is undefined if this NestedInteger holds a nested list * // So before calling this method, you should have a check * func (n NestedInteger) GetInteger() int {} * * // Set this NestedInteger to hold a single integer. * func (n *NestedInteger) SetInteger(value int) {} * * // Set this NestedInteger to hold a nested list and adds a nested integer to it. * func (n *NestedInteger) Add(elem NestedInteger) {} * * // Return the nested list that this NestedInteger holds, if it holds a nested list * // The list length is zero if this NestedInteger holds a single integer * // You can access NestedInteger's List element directly if you want to modify it * func (n NestedInteger) GetList() []*NestedInteger {} */ func deserialize(s string) *NestedInteger { if s[0] != '[' { num, _ := strconv.Atoi(s) ni := &NestedInteger{} ni.SetInteger(num) return ni } stack, num, negative := []*NestedInteger{}, 0, false for i, ch := range s { if ch == '-' { negative = true } else if unicode.IsDigit(ch) { num = num*10 + int(ch-'0') } else if ch == '[' { stack = append(stack, &NestedInteger{}) } else if ch == ',' || ch == ']' { if unicode.IsDigit(rune(s[i-1])) { if negative { num = -num } ni := NestedInteger{} ni.SetInteger(num) stack[len(stack)-1].Add(ni) } num, negative = 0, false if ch == ']' && len(stack) > 1 { stack[len(stack)-2].Add(*stack[len(stack)-1]) stack = stack[:len(stack)-1] } } } return stack[len(stack)-1] }
javascript 解法, 执行用时: 92 ms, 内存消耗: 53.1 MB, 提交时间: 2022-12-09 09:59:57
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * function NestedInteger() { * * Return true if this NestedInteger holds a single integer, rather than a nested list. * @return {boolean} * this.isInteger = function() { * ... * }; * * Return the single integer that this NestedInteger holds, if it holds a single integer * Return null if this NestedInteger holds a nested list * @return {integer} * this.getInteger = function() { * ... * }; * * Set this NestedInteger to hold a single integer equal to value. * @return {void} * this.setInteger = function(value) { * ... * }; * * Set this NestedInteger to hold a nested list and adds a nested integer elem to it. * @return {void} * this.add = function(elem) { * ... * }; * * Return the nested list that this NestedInteger holds, if it holds a nested list * Return null if this NestedInteger holds a single integer * @return {NestedInteger[]} * this.getList = function() { * ... * }; * }; */ /** * @param {string} s * @return {NestedInteger} */ var deserialize = function(s) { if (s[0] !== '[') { return new NestedInteger(parseInt(s)); } const stack = []; let num = 0; let negative = false; for (let i = 0; i < s.length; i++) { const c = s[i]; if (c === '-') { negative = true; } else if (isDigit(c)) { num = num * 10 + c.charCodeAt() - '0'.charCodeAt(); } else if (c === '[') { stack.push(new NestedInteger()); } else if (c === ',' || c === ']') { if (isDigit(s[i - 1])) { if (negative) { num *= -1; } stack[stack.length - 1].add(new NestedInteger(num)); } num = 0; negative = false; if (c === ']' && stack.length > 1) { const ni = stack.pop(); stack[stack.length - 1].add(ni); } } } return stack.pop(); }; const isDigit = (ch) => { return parseFloat(ch).toString() === "NaN" ? false : true; }
java 解法, 执行用时: 7 ms, 内存消耗: 41.5 MB, 提交时间: 2022-12-09 09:59:40
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * public interface NestedInteger { * // Constructor initializes an empty nested list. * public NestedInteger(); * * // Constructor initializes a single integer. * public NestedInteger(int value); * * // @return true if this NestedInteger holds a single integer, rather than a nested list. * public boolean isInteger(); * * // @return the single integer that this NestedInteger holds, if it holds a single integer * // Return null if this NestedInteger holds a nested list * public Integer getInteger(); * * // Set this NestedInteger to hold a single integer. * public void setInteger(int value); * * // Set this NestedInteger to hold a nested list and adds a nested integer to it. * public void add(NestedInteger ni); * * // @return the nested list that this NestedInteger holds, if it holds a nested list * // Return empty list if this NestedInteger holds a single integer * public List<NestedInteger> getList(); * } */ class Solution { public NestedInteger deserialize(String s) { if (s.charAt(0) != '[') { return new NestedInteger(Integer.parseInt(s)); } Deque<NestedInteger> stack = new ArrayDeque<NestedInteger>(); int num = 0; boolean negative = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '-') { negative = true; } else if (Character.isDigit(c)) { num = num * 10 + c - '0'; } else if (c == '[') { stack.push(new NestedInteger()); } else if (c == ',' || c == ']') { if (Character.isDigit(s.charAt(i - 1))) { if (negative) { num *= -1; } stack.peek().add(new NestedInteger(num)); } num = 0; negative = false; if (c == ']' && stack.size() > 1) { NestedInteger ni = stack.pop(); stack.peek().add(ni); } } } return stack.pop(); } }
python3 解法, 执行用时: 64 ms, 内存消耗: 18.4 MB, 提交时间: 2022-12-09 09:59:22
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger: # def __init__(self, value=None): # """ # If value is not specified, initializes an empty list. # Otherwise initializes a single integer equal to value. # """ # # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def add(self, elem): # """ # Set this NestedInteger to hold a nested list and adds a nested integer elem to it. # :rtype void # """ # # def setInteger(self, value): # """ # Set this NestedInteger to hold a single integer equal to value. # :rtype void # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class Solution: def deserialize(self, s: str) -> NestedInteger: if s[0] != '[': return NestedInteger(int(s)) stack, num, negative = [], 0, False for i, c in enumerate(s): if c == '-': negative = True elif c.isdigit(): num = num * 10 + int(c) elif c == '[': stack.append(NestedInteger()) elif c in ',]': if s[i-1].isdigit(): if negative: num = -num stack[-1].add(NestedInteger(num)) num, negative = 0, False if c == ']' and len(stack) > 1: stack[-2].add(stack.pop()) return stack.pop()