Given a nested list of integers represented as a string, implement a parser to deserialize it. Each element was either an integer, or a list--whose elements may also is integers or other lists. Note:you may assume , the string is well-Formed:string is non-empty. String does not contain white spaces. String contains only digits0-9, [,- ,, ]. Example1: Given s= "324", you shouldreturnA Nestedinteger object which contains a single integer 324. Example2: Given s= "[123,[456,[789]]", Return a Nestedinteger object containing a nested list with2elements:1. An integer containing value 123.2. A nested list containing the elements:i. An integer containing value456. Ii. A nested list with one element:a. An integer containing value789.
This is usually used with a stack, stack top is the current Nestedinteger, you can add new elements to it.
Note that the 47 line judgment is critical, incidentally handling "[]," after the parentheses are comma-case
1 /**2 *//This is the interface, allows for creating nested lists.3 *//should not implement it, or speculate on its implementation4 * Public interface Nestedinteger {5 *//Constructor Initializes an empty nested list.6 * public Nestedinteger ();7 *8 *//Constructor Initializes a single integer.9 * Public Nestedinteger (int value);Ten * One * // @returntrue if this nestedinteger holds a single integer, rather than a nested list. A * Public boolean isinteger (); - * - * // @returnThe single integer Nestedinteger holds, if it holds a single integer the *//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 an integer to it. A * public void Add (Nestedinteger ni); at * - * // @returnthe nested list that this nestedinteger holds, if it holds a nested list - *//Return NULL if this nestedinteger holds a single integer - * Public list<nestedinteger> getList (); - * } - */ in Public classSolution { - PublicNestedinteger Deserialize (String s) { to if(!s.startswith ("[")) { + return NewNestedinteger (Integer.parseint (s)); - } theNestedinteger res =NewNestedinteger (); *Stack<nestedinteger> st =NewStack<nestedinteger>(); $ St.push (res);Panax Notoginseng intStart = 1; - for(intI=1; I<s.length (); i++) { the Charc =S.charat (i); + if(c = = ' [') { ANestedinteger ni =NewNestedinteger (); the St.peek (). Add (NI); + St.push (NI); -Start = I+1; $ } $ Else if(c== ', ' | | c== ') ') { - if(I >start) { - intval =Integer.parseint (s.substring (Start, i)); theSt.peek (). Add (NewNestedinteger (Val)); - }WuyiStart = I+1; the if(c = = '] ') St.pop (); - } Wu } - returnRes; About } $}
Leetcode:mini Parser