/** * // 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 null if this NestedInteger holds a single integer * public List<NestedInteger> getList(); * } */ class{ public NestedInteger deserialize(String s){ Stack<NestedInteger> stack = new Stack<>(); if(s.charAt(0) != '['){ returnnew NestedInteger(Integer.valueOf(s)); } NestedInteger fakeBaba = new NestedInteger(); int start = 0; stack.push(fakeBaba); for(int i=0; i < s.length(); i++){ char c = s.charAt(i); if( c == '-' || '0'<= c && c <= '9'){ continue; } if(c == '['){ NestedInteger nested = new NestedInteger(); stack.peek().add(nested); stack.push(nested); }else{ if(s.charAt(i-1) >= '0' && s.charAt(i-1) <= '9'){ int num = Integer.valueOf(s.substring(start, i)); NestedInteger nested = new NestedInteger(num); stack.peek().add(nested); } if(c == ']'){ stack.pop();// '['时,既peek又push了,所以当']'或','时 给peek加就相当于给前一个也加了; } } start = i+1; } return stack.peek().getList().get(0); } }
近期评论