高级农民
- 积分
- 2716
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-6-18
- 最后登录
- 1970-1-1
|
可以对NestedInteger接口实现两个子类,一个处理单个整数的情况,另一个处理List的情况:
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Stack;
- public class Main {
- public static void main(String[] args) {
- // 测试数据
- // [1, [2, 3], [[4, [], [5], 6, 7], 8], 9]
- NestedInteger nestedList = new NestedList(
- new SingletonInteger(1),
- new NestedList(
- new SingletonInteger(2),
- new SingletonInteger(3)
- ),
- new NestedList(
- new NestedList(
- new SingletonInteger(4),
- new NestedList(),
- new NestedList(
- new SingletonInteger(5)
- ),
- new SingletonInteger(6),
- new SingletonInteger(7)
- ),
- new SingletonInteger(8)
- ),
- new SingletonInteger(9)
- );
- NestedIterator it = new NestedIterator(nestedList.getList());
- while (it.hasNext()) {
- System.out.println(it.next());
- }
- }
- }
- interface NestedInteger {
- public boolean isInteger();
- public Integer getInteger();
- public List<NestedInteger> getList();
- }
- // 处理单个整数
- class SingletonInteger implements NestedInteger {
- private int value;
- public SingletonInteger(int value) {
- this.value = value;
- }
- @Override
- public boolean isInteger() {
- return true;
- }
- @Override
- public Integer getInteger() {
- return value;
- }
- @Override
- public List<NestedInteger> getList() {
- return null;
- }
- }
- // 处理List
- class NestedList implements NestedInteger {
- private List<NestedInteger> list = new ArrayList<NestedInteger>();
- public NestedList(NestedInteger ...values) {
- for (NestedInteger value : values) {
- list.add(value);
- }
- }
- @Override
- public boolean isInteger() {
- return false;
- }
- @Override
- public Integer getInteger() {
- return null;
- }
- @Override
- public List<NestedInteger> getList() {
- return list;
- }
- }
- // LC 341
- class NestedIterator implements Iterator<Integer> {
- private Stack<Iterator<NestedInteger>> state;
- private boolean hasNextValue;
- private Integer nextValue;
- public NestedIterator(List<NestedInteger> nestedList) {
- state = new Stack<Iterator<NestedInteger>>();
- state.push(nestedList.iterator());
- fetchNext();
- }
- @Override
- public Integer next() {
- Integer retValue = nextValue;
- fetchNext();
- return retValue;
- }
- @Override
- public boolean hasNext() {
- return hasNextValue;
- }
- private void fetchNext() {
- while (!state.isEmpty()) {
- Iterator<NestedInteger> it = state.pop();
- if (it.hasNext()) {
- NestedInteger ni = it.next();
- state.push(it);
- if (ni.isInteger()) {
- hasNextValue = true;
- nextValue = ni.getInteger();
- return;
- }
- state.push(ni.getList().iterator());
- }
- }
- hasNextValue = false;
- }
- }
复制代码 |
|